How to mock function props in React unit tests #16867
-
We are currently considering moving from Jest+RTL to Cypress for component unit tests in a React web app. I like the syntax very much (aside from the chai/mocha style assertions) but I can't figure out how to correctly test that function props have been called. For example a simple custom text field. In Jest we would write a test like so and it would pass: it("should parse user input", async () => {
const changeFn = jest.fn();
const dom = render(
<TimeField
label="Test"
value={10}
onChange={changeFn}
/>
);
const textBox = dom.getByRole("textbox");
fireEvent.change(textBox, { target: { value: "30m" } });
fireEvent.blur(textBox);
expect(changeFn).toHaveBeenCalledTimes(1);
} I am trying to duplicate that behaviour with Cypress like so but can't get this test to pass: it("should parse user input", () => {
const changeFn = cy.stub();
mount(
<TimeField label="Test" value={0} onChange={changeFn} />
);
cy.get("body").find("input").type("{selectall}30m").blur();
expect(blurFn).to.be.called;
}); Is this not how function props are meant to be tested or am I missing something else? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I found the answer myself: Apparently the code I wrote is just fine but Cypress executes the assertion block before the blurevent finishes. So we need to move the assertion into a cy.get("body").find("input").type("{selectall}30m").blur().then(() => { /* assertion here */ }) |
Beta Was this translation helpful? Give feedback.
I found the answer myself: Apparently the code I wrote is just fine but Cypress executes the assertion block before the blurevent finishes. So we need to move the assertion into a
.then()
afterblur()
: