小编Pav*_*sha的帖子

测试时如何触发功能组件的卸载?

我使用“useEffect”来实现功能组件中“componentWillUnmount”的功能。如何在使用 Jest/Enzyme 测试组件时触发它?

我的组件:

const myComp = () => {
  useEffect(() => () => {
    console.log('Unmounted');
  }, []);
  return <div>Test</div>;
}
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs enzyme react-hooks

6
推荐指数
2
解决办法
2万
查看次数

如何使用 JEST、Enzyme 在 React 中测试自定义钩子?

我有一个像下面这样的自定义钩子

const useSum = (a = 1, b = 1) => {
  const [sum, setSum] = useState(a + b);

  useEffect(() => {
    setSum(a + b);
  }, [a, b]);

  return sum;
}
Run Code Online (Sandbox Code Playgroud)

我在我的 funcionat 组件中使用它

const MyFuncComp = () => {
  const sum = useSum(1, 2);
  return (
   <div>{sum}</div>
  );
}
Run Code Online (Sandbox Code Playgroud)

在测试用例中,我有这样的

describe('Testing MyFuncComp', () => {
  const myFuncComp = mount(<MyFuncComp />);
  it('should have value of sum', () => {

    const expected = '3';
    const received = myFuncComp.find('div').text();
    expect(received).toEqual(expected);    
  });
}) …
Run Code Online (Sandbox Code Playgroud)

unit-testing reactjs jestjs enzyme react-hooks

5
推荐指数
1
解决办法
2962
查看次数

标签 统计

enzyme ×2

jestjs ×2

react-hooks ×2

reactjs ×2

unit-testing ×1