首页 > 解决方案 > “setProps()”没有在 Jest 中触发“useEffect”

问题描述

当我在测试用例中更新功能组件的道具时,它不会触发 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);
  });  
});

标签: javascriptreactjsjestjsreact-hooksenzyme

解决方案


useEffect()并且useLayoutEffect()不要在 React 浅渲染器中被调用。请参阅组件浅渲染时未调用 useEffect 此问题

您应该使用该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",

推荐阅读