【发布时间】:2022-01-04 14:22:58
【问题描述】:
我尝试测试给定的操作是否真的在组件中被触发。如果带有操作的回调作为道具传递可能很容易,但我不清楚在我的情况下如何做到这一点。这是组件:
export const Modal = (props: appendProps): JSX.Element => {
const { items, activeScope } = props;
const primary = items[0] === activeScope;
const { closeInput, appendItem } = useDispatchAction();
{...}
<Button
variant="contained"
size="large"
className="modal-content__button"
color="secondary"
onClick={() => {
closeInput();
}}
>
Zamknij
</Button>
useDispatchAction 如下:
import { useDispatch } from 'react-redux';
import { bindActionCreators } from 'redux';
import { actionCreators } from '../redux';
const useDispatchAction = () => {
const dispatch = useDispatch();
return bindActionCreators(actionCreators, dispatch);
};
export default useDispatchAction;
并在下面测试自己
describe('Test button actions', () => {
const closeInput = jest.fn();
jest.mock('../../src/hooks/useDispatchAction', () => ({closeInput}));
beforeEach(() => {
render(<Modal />);
});
afterEach(() => cleanup());
test('component fires closeInput', () => {
const closeButton = screen.getByRole('button', { name: 'Zamknij' });
expect(closeButton).toBeInTheDocument();
userEvent.click(closeButton);
expect(closeInput).toBeCalled();
});
});
但这一直告诉我该函数已被调用 0 次而不是至少 1 次
【问题讨论】: