如何使用 jest 测试 useSelector

问题描述 投票:0回答:1

所以,我在选择器中定义

const = saveAndExitSelector = createSelector((state:IAppStoreState)=> state.Abc.data, ({abc,xyz,mno}) = ({abc,xyz,mno}) );

定义它之后,我将其传递为

Const {abc,xyz,mno} = useSelector(saveAndExitSelector);

常量输入 = [acb,xyz,mno]

我在一个按钮中定义其 onclick,我调度和事件并发送输入

javascript unit-testing react-redux jestjs
1个回答
0
投票

要使用 Jest 和 React 测试库测试

useSelector
钩子和
onClick
事件处理程序,您需要模拟 Redux 存储和选择器函数。这是测试此代码的分步方法。

  1. 首先,我们稍微重构一下组件,使其更容易测试:

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>

  1. 现在,让我们为这个组件编写一个测试:

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>

© www.soinside.com 2019 - 2024. All rights reserved.