Cypress 函数模拟类似于 jest.fn

ble*_*enm 3 cypress cypress-component-test-runner

我在 React 中尝试 cypress 组件测试,但对一些基本的东西有点困惑,比如如何断言点击处理程序。

开玩笑我可以做类似的事情

const hideMock = jest.fn();

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

await cancel();

expect(hideMock).toBeCalledTimes(1);
Run Code Online (Sandbox Code Playgroud)

我该如何使用const hideMock = jest.fn();柏树间谍?

这就是我得到的

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;
  });
Run Code Online (Sandbox Code Playgroud)

jjh*_*ero 6

我没有太多进行组件测试,但使用间谍/存根应该相对相同。对于您的情况,您需要向间谍/存根添加别名,使用 cy.get('@alias'),然后对其使用 sinon 断言。

我使用 .stub() 因为您只想检查单击处理程序是否被调用。

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')
  });

Run Code Online (Sandbox Code Playgroud)