小编ott*_*tto的帖子

useEffect 钩子没有被 jest.spyOn 嘲笑

我是 React Hooks 的新手,我想要实现的是测试一个 React 组件(称为 CardFooter),该组件包含对 useEffect 钩子的调用,该钩子被触发并修改了全局上下文变量。

CardFooter.js:

const CardFooter = props => {
  const [localState, setLocalState] = useState({
    attachmentError: false
  });
  const globalContext = useContext(GlobalContext);
  React.useEffect(()=> {
    setLocalState({
    ...localState,
    attachmentError: globalContext.data.attachmentError
  });
 },[globalContext.data.attachmentError]);
}
Run Code Online (Sandbox Code Playgroud)

CardFooter.test.js:

import Enzyme, { shallow } from 'enzyme';    
Enzyme.configure({ adapter: new Adapter() });
describe('<CardFooter  />', () => {
  let useEffect;
  const mockUseEffect = () => {
    useEffect.mockImplementation(f => f());
  };

  useEffect = jest.spyOn(React, "useEffect");
  mockUseEffect(); //

  it('should render correctly with no props.', () …
Run Code Online (Sandbox Code Playgroud)

javascript jestjs react-hooks use-effect

7
推荐指数
1
解决办法
7183
查看次数

标签 统计

javascript ×1

jestjs ×1

react-hooks ×1

use-effect ×1