“setProps()”不会在 Jest 中触发“useEffect”

时间:2021-04-29 07:22:07

标签: javascript reactjs jestjs react-hooks enzyme

当我在测试用例中更新功能组件的 props 时,它不会触发 useEffect。但是它正在更新 myComp 中的道具。

组件示例:

const myComp = ({userId, myAction}) => {
 useEffect(() => {
  myAction(userId);
 }, [userId]);

  return <div>Test</div>
}

测试用例示例:

.....
describe('Testing MyComp', () => {
  it('should call myAction with userID', () => {
    const userId = 'testId';
    wrapper.setProps({userId});
    expect(myAction).toHaveBeenCalledWith(userId);
  });  
});

1 个答案:

答案 0 :(得分:1)

useEffect()useLayoutEffect() 在 React 浅层渲染器中不会被调用。请参阅 useEffect not called when the component is shallow renderered this issue

您应该使用 mount 函数。

例如

index.tsx

import React, { useEffect } from 'react';

export const MyComp = ({ userId, myAction }) => {
  useEffect(() => {
    myAction(userId);
  }, [userId]);

  return <div>Test</div>;
};

index.test.tsx

import React from 'react';
import { mount } from 'enzyme';
import { MyComp } from './';

describe('67312763', () => {
  it('should pass', () => {
    const props = {
      userId: '1',
      myAction: jest.fn(),
    };
    const wrapper = mount(<MyComp {...props} />);
    expect(props.myAction).toHaveBeenCalledWith('1');
    const userId = '2';
    wrapper.setProps({ userId });
    expect(props.myAction).toHaveBeenCalledWith('2');
  });
});

测试结果:

 PASS  examples/67312763/index.test.tsx (7.221 s)
  67312763
    ✓ should pass (31 ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |     100 |      100 |     100 |     100 |                   
 index.tsx |     100 |      100 |     100 |     100 |                   
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        7.731 s

包版本:

"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.5",
"jest": "^26.6.3",
"jest-enzyme": "^7.1.2",
"react": "^16.14.0",