cypresscypress-component-test-runner

Cypress function mocking similar to jest.fn


Im trying out cypress component test in React and Im kinda confused on some basic stuff like how to assert click handlers.

In Jest I can do something like

const hideMock = jest.fn();

renderWithProviders(
    <EmployeeCreationWizard
        hide={hideMock}
        isVisible={true}
        employeeId={123}
    />,
);

await cancel();

expect(hideMock).toBeCalledTimes(1);

How can I do the const hideMock = jest.fn(); with cypress spies?

This is what I got

it.only('invoke hide() once upon clicking on cancel button', () => {
    const hideSpy = cy.spy();
    cy.interceptEmployeeCreationWizard();
    cy.mount(
      <EmployeeCreationWizard
        isVisible={true}
        hide={hideSpy}
        employeeId={123}
      />,
    );

    cy.findByTestId('employee-wizard-drawer-cancel').click();
    cy.get('[data-test-id="employee-wizard-drawer-close"]').click();
    // eslint-disable-next-line @typescript-eslint/no-unused-expressions
    // expect(hideSpy).to.be.calledOnce;
  });

Solution

  • I have not worked with component testing much but using spy/stub should be relatively the same. For your case, you'll want to add an alias to your spy/stub, use cy.get('@alias'), and then use sinon assertions against it.

    I use .stub() since you want to only check the click handler is called.

    it.only('invoke hide() once upon clicking on cancel button', () => {
        cy.interceptEmployeeCreationWizard();
        cy.mount(
          <EmployeeCreationWizard
            isVisible={true}
            hide={cy.stub().as('hide')}
            employeeId={123}
          />,
        );
    
        cy.findByTestId('employee-wizard-drawer-cancel').click();
        cy.get('[data-test-id="employee-wizard-drawer-close"]').click();
        cy.get('@hide').should('have.been.called')
      });