所以,我在选择器中定义
const = saveAndExitSelector = createSelector((state:IAppStoreState)=> state.Abc.data, ({abc,xyz,mno}) = ({abc,xyz,mno}) );
定义它之后,我将其传递为
Const {abc,xyz,mno} = useSelector(saveAndExitSelector);
常量输入 = [acb,xyz,mno]
我在一个按钮中定义其 onclick,我调度和事件并发送输入
要使用 Jest 和 React 测试库测试
useSelector
钩子和 onClick
事件处理程序,您需要模拟 Redux 存储和选择器函数。这是测试此代码的分步方法。
import React from 'react';
import { useSelector } from 'react-redux';
import { createSelector } from 'reselect';
const saveAndExitSelector = createSelector(
(state) => state.Abc.data,
({ abc, xyz, mno }) => ({ abc, xyz, mno })
);
export const MyComponent = ({ actions, eventName }) => {
const { abc, xyz, mno } = useSelector(saveAndExitSelector);
const input = [abc, xyz, mno];
const handleClick = () => actions.dispatchEvent(eventName, input);
return <button onClick={handleClick}>Save and Exit</button>;
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import { useSelector } from 'react-redux';
import { MyComponent } from './MyComponent';
// Mock react-redux hooks
jest.mock('react-redux', () => ({
useSelector: jest.fn(),
}));
describe('MyComponent', () => {
const mockActions = {
dispatchEvent: jest.fn(),
};
const mockEventName = 'SAVE_AND_EXIT';
beforeEach(() => {
useSelector.mockClear();
mockActions.dispatchEvent.mockClear();
});
it('should dispatch event with correct input on button click', () => {
// Mock the selector return value
useSelector.mockReturnValue({ abc: 1, xyz: 2, mno: 3 });
const { getByText } = render(
<MyComponent actions={mockActions} eventName={mockEventName} />
);
const button = getByText('Save and Exit');
fireEvent.click(button);
expect(mockActions.dispatchEvent).toHaveBeenCalledWith(
mockEventName,
[1, 2, 3]
);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>