useContext 值在测试中返回 undefined

IT技术 reactjs jestjs enzyme
2021-04-30 16:24:57

我是测试和使用 Enzyme 和 Jest 编写非常简单的测试的新手。我只想检查组件是否呈现。但是,(我猜)因为我的组件使用了useContext钩子,所以测试用例会自动为所有来自上下文的值返回 undefined。

在组件中:

const { count, setCount } = useContext(Context);

测试用例:

it('should render', () => {
  const component = shallow(<MyComponent />);
  const wrapper = component.find('myClassName');
  expect(wrapper.length).toBe(1);
});

测试结果:无法读取未定义的属性“计数”。我不知道我做错了什么。是否有一种简单的方法可以始终与useContext其他钩子一起使用来测试简单的事情?

1个回答

我认为这里的问题是当你浅渲染一个组件时,Context会被忽略。因此,请尝试安装您的组件,而不是像这样进行浅层渲染:

import { mount } from "enzyme"; // mount instead of `shallow` here

...
it('should render', () => {
  const component = mount(<MyComponent />); // `mount` here as well
  const wrapper = component.find('myClassName');
  expect(wrapper.length).toBe(1);
});