无法模拟调度函数以在 React 的测试用例中使用以跟踪从组件触发的单击事件
Unable to mock a dispatch function to use in test case in React to track click event been fired from the component
我正在尝试编写一个测试用例来模拟调度。基本上有一个组件,其中从事件处理程序中调用调度函数。所以我想检查该按钮是否被点击。但是做不到。
-----Lgin.test.ts----
import {render,screen, fireEvent} from '@testing-library/react'
import Login from './Login';
import {Provider} from 'react-redux';
import configureStore from 'redux-mock-store';
import Thunk from 'redux-thunk'
import * as redux from "react-redux";
it(" Test button click", async()=>{
const initialState = {
username: '',
password: '',
isSubmit: false
};
const mockStore = configureStore([Thunk]);
let store = mockStore(initialState);
const useDispatchSpy = jest.spyOn(redux, 'useDispatch');
render(
<Provider store={store}>
<Login />
</Provider>
);
const rObj = screen.getByTestId("lginsbmit");
fireEvent.click(rObj);
expect(useDispatchSpy).toHaveBeenCalled();
useDispatchSpy.mockClear();
})
大家好,我做了这些更改并且对我有用,希望这对其他人也有帮助:
it(" RTL test to check button clicked i.e internally track dispatch function clicked", async()=>{
let store = mockStore(initialState);
const useDispatchSpy = jest.spyOn(redux, 'useDispatch');
const mockDispatchFn = jest.fn()
useDispatchSpy.mockReturnValue(mockDispatchFn);
render(
<Provider store={store}>
<Login />
</Provider>
);
const rObj = screen.getByTestId("lginsbmit");
fireEvent.click(rObj);
expect(mockDispatchFn).toHaveBeenCalled();
//teardown
useDispatchSpy.mockClear();
})
我正在尝试编写一个测试用例来模拟调度。基本上有一个组件,其中从事件处理程序中调用调度函数。所以我想检查该按钮是否被点击。但是做不到。
-----Lgin.test.ts----
import {render,screen, fireEvent} from '@testing-library/react'
import Login from './Login';
import {Provider} from 'react-redux';
import configureStore from 'redux-mock-store';
import Thunk from 'redux-thunk'
import * as redux from "react-redux";
it(" Test button click", async()=>{
const initialState = {
username: '',
password: '',
isSubmit: false
};
const mockStore = configureStore([Thunk]);
let store = mockStore(initialState);
const useDispatchSpy = jest.spyOn(redux, 'useDispatch');
render(
<Provider store={store}>
<Login />
</Provider>
);
const rObj = screen.getByTestId("lginsbmit");
fireEvent.click(rObj);
expect(useDispatchSpy).toHaveBeenCalled();
useDispatchSpy.mockClear();
})
大家好,我做了这些更改并且对我有用,希望这对其他人也有帮助:
it(" RTL test to check button clicked i.e internally track dispatch function clicked", async()=>{
let store = mockStore(initialState);
const useDispatchSpy = jest.spyOn(redux, 'useDispatch');
const mockDispatchFn = jest.fn()
useDispatchSpy.mockReturnValue(mockDispatchFn);
render(
<Provider store={store}>
<Login />
</Provider>
);
const rObj = screen.getByTestId("lginsbmit");
fireEvent.click(rObj);
expect(mockDispatchFn).toHaveBeenCalled();
//teardown
useDispatchSpy.mockClear();
})