如何在Jest中测试redux选择器



我想测试以下选择器:

export const getApp = (): IApp | null => {
return useSelector<IState, IApp | null>((state) => state.appState.app);
};

这就是测试:

import { appSelectors, getApp } from '../appSelectors';
import thunk from 'redux-thunk';
import { IApp } from '...common...interfaces';
let store: any = null;
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
const createMockStore = () => {
store = mockStore(testsStore.initialState);
};
describe('apps selectors', () => {
test('getApp', () => {
const mockedApp: IApp = {
id: 'mocked_id',
name: 'mocked_id',
};

// ... >> modify the testsStore.initialState here ...
createMockStore();
expect(getApp()).toEqual(mockedApp);
});
});

这是我得到的错误:无效的挂钩调用。钩子只能在函数组件的主体内部调用。可能会发生这种情况

for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
7 |
8 | export const getApp = (): IApp | null => {
>  9 |   return useSelector<IState, IApp | null>((state) => state.appState.app);
|          ^
10 | };

如何测试此选择器?

谢谢。

(state) => state.appState.app函数是一个选择器,它可以单独提取和测试,但由于它很简单,它可以与getApp一起测试。

getAppuseSelector是自定义挂钩,它们应该由React渲染器调用,而不是直接调用。这需要使用虚拟组件来完成。由于开发人员可以完全控制它,因此需要格式化该值并将其转换为布局,以便可以明确断言:

const Dummy = () => {
const app = getApp();
return <div>
<div data-testid="app-id">{app.id}</div>
<div data-testid="app-name">{app.name}</div>
</div>;
};
const wrapper = mount(<Dummy/>);
expect(wrapper.find('[data-testid="app-id"]').text()).toBe('mocked id');
expect(wrapper.find('[data-testid="app-name"]').text()).toBe('mocked name');

其中data-testid属性是其他测试库使用的约定,尤其是适用于这种灰盒测试的测试库。

最新更新