【问题标题】:useEffect hook not being mocked by jest.spyOnuseEffect 钩子没有被 jest.spyOn 嘲笑
【发布时间】:2020-04-23 09:48:16
【问题描述】:

我是 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]);
}

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.', () => {
  }

  const mockUseEffect = () => {
    useEffect.mockImplementation(f => f());
  };

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

  const wrapper = shallow(<CardFooter />);
  expect(toJson(wrapper)).toMatchSnapshot();

});

我在运行测试时遇到的错误是:

TypeError: Cannot read property 'attachmentError' of undefined

我尝试了这里介绍的方法:https://medium.com/@pylnata/testing-react-functional-component-using-hooks-useeffect-usedispatch-and-useselector-in-shallow-9cfbc74f62fb。然而,浅层似乎没有选择模拟的 useEffect 实现。我还尝试模拟 useContext 和 globalContext.data.attachmentError。似乎没有任何效果。

【问题讨论】:

  • 您是否尝试过将模拟实现移动到模块范围(在描述块之外)?例如 const useEffect = jest.spyOn(React, "useEffect").mockImplementation(() =&gt; {}) 就在 describe() 之前。
  • 它适用于 .mount() 和

标签: javascript jestjs react-hooks use-effect


【解决方案1】:

试试这个。注意“jest.spyOn”被放置在“beforeEach”中

  beforeEach(() => {
    jest.spyOn(React, "useEffect").mockImplementationOnce(cb => cb()());
    
     // .... other things ....
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-21
    • 2018-12-24
    • 2015-06-06
    • 1970-01-01
    相关资源
    最近更新 更多