簡體   English   中英

如何使用 React 測試庫 + Jest 模擬測試函數

[英]How to mock functions for testing using the React Testing Library + Jest

我正在使用 jest/react-testing-library 測試反應組件,無論我嘗試什么,我都無法在我的測試中正確模擬函數。 每當我運行調用我試圖模擬的組件功能之一的 fireEvent 時,它都會調用原始的 function 而不是我試圖模擬的 function。 我查看了有關 StackOverflow 的所有相關問題,但沒有一個解決方案對我有用。

我試過同時使用 jest.fn() 和 jest.spyOn() ,但都沒有奏效。

我的模擬(對於來自組件“PasswordResetConfirmation”的 function)如下:

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

對於如何讓這個 function 模擬工作的任何建議,我將不勝感激。

作為后續行動,我還嘗試在這些測試中從不同的文件(不是我當前正在測試的組件)模擬 function,並且在調用原始 function 而不是模擬時遇到了類似的問題。

謝謝!

也許下面的代碼也可能對您有用。

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

嘗試使用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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM