【问题标题】:How to mock functions for testing using the React Testing Library + Jest如何使用 React 测试库 + Jest 模拟测试函数
【发布时间】:2020-07-23 04:55:48
【问题描述】:

我正在使用 jest/react-testing-library 测试反应组件,无论我尝试什么,我都无法在我的测试中正确地模拟函数。每当我运行一个调用我试图模拟的组件函数之一的 fireEvent 时,它都会调用原始函数而不是我试图模拟的函数。我查看了 StackOverflow 上的所有相关问题,但没有一个解决方案适合我。

我尝试过同时使用 jest.fn() 和 jest.spyOn() 都没有成功。

我的模拟(对于来自组件“PasswordResetConfirmation”的函数)如下:

PasswordResetConfirmation.handleOkay = jest.fn(() => true)

test('handleOkay method is called when user clicks Okay button', () => {
  const {getByTestId} = render(<MemoryRouter><PasswordResetConfirmation/> </MemoryRouter>)

  let button = getByTestId('reset-confirm-button')
  expect(button).toBeInTheDocument();

  fireEvent.click(button) // this is where the mocked handleOkay method should be called but isn't
})

我将不胜感激有关如何让这个函数模拟工作的任何建议。

作为后续行动,我还尝试在这些测试中模拟来自不同文件(而不是来自我当前正在测试的组件)的函数,并且在调用原始函数而不是模拟。

谢谢!

【问题讨论】:

  • 不熟悉你正在使用的一些东西,但你可以试试 button.simulate('click') 吗?
  • @TalmacelMarianSilviu 可用于酶但不能用于测试库
  • 根据库的开发人员的说法,这是故意以模拟组件方法很难testing-library.com/docs/dom-testing-library/faq的方式完成的。

标签: javascript reactjs react-redux jestjs react-testing-library


【解决方案1】:

也许下面的代码对你也有用。

    const mockFn = jest.fn(() => true);
    const { getByTestId } = render(
        <Provider store={store}>
            <RandomMeals/>
        </Provider>
        );
    const button = getByTestId("random-meals-button-test");
    fireEvent.click(button);
    expect(mockFn()).toBe(true);

【讨论】:

    【解决方案2】:

    enzymeenzyme-react-adapter-15 试试(你必须通过npm 安装)

    然后像这样测试它(注意你的 handleOk() 不能是箭头函数):

    import Enzyme, { mount} from 'enzyme';
    import Adapter from 'enzyme-adapter-react-16';
     
    Enzyme.configure({ adapter: new Adapter() });
    
    
    it('...', (done) => {
        const mockHandleOk = jest.spyOn(PasswordResetConfirmation.prototype, 'handleOk').mockImplementationOnce(() => {});
    
        const wrapper = mount(
            <MemoryRouter>
                <PasswordResetConfirmation/>
            </MemoryRouter>
        );
    
        const button = wrapper.find('#reset-confirm-button');
        expect(button).toHaveLength(1);
    
        button.simulate('click');
    
        setTimeout(function() {
            expect(mockHandleOk).toHaveBeenCalled();
        }, 500);
    }
    

    【讨论】:

    • 这个答案使事情变得复杂。您不仅建议他们切换库,而且您从示例中的那个中建议了错误的适配器,而且您并没有真正解释您的测试到底在做什么。比如超时是怎么回事
    • 是的,你是对的...超时是等待异步函数,如果有的话
    猜你喜欢
    • 1970-01-01
    • 2021-12-03
    • 2019-04-22
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 2018-01-26
    • 2021-06-04
    • 2019-07-22
    相关资源
    最近更新 更多