我编写了一个功能组件,它使用 React.useReducer() 钩子(Hook)作为代码的一部分。
该组件有一个 reducer 和 Action 作为其中的一部分。我认为与其单独测试 reducer 功能和操作,不如编写一个集成测试:
IntegrationTest.js
describe('integration test for reducers and actions', () => {
const initialState = { secretWord: 'party' };
test('dispatch actions and verify updated state', () => {
const [state, dispatch] = React.useReducer(reducer, initialState);
dispatch({ type: setSecretWord, payload: 'train' });
expect(state).toEqual({ secretWord: 'train' });
});
});
当我运行测试时,我收到错误:
无效的 Hook 调用。钩子(Hook)只能在函数组件的主体内部调用。发生这种情况可能是由于以下原因之一: 1.您的React和渲染器版本可能不匹配(例如React DOM) 2. 你可能违反了 Hooks 规则 3.您可能在同一个应用程序中拥有多个React副本
在这种情况下如何编写集成测试,因为钩子(Hook)只能在组件内调用?
最佳答案
尝试更新代码如下 - 使用 renderHook
import { renderHook } from '@testing-library/react-hooks';
describe('integration test for reducers and actions', () => {
const initialState = { secretWord: 'party' };
test('dispatch actions and verify updated state', () => {
const [state, dispatch] = renderHook(() => useReducer(reducer, initialState));
dispatch({ type: setSecretWord, payload: 'train' });
expect(state).toEqual({ secretWord: 'train' });
});
});
关于reactjs - React Hooks - useReducer() - 集成测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60991857/