首页 > 解决方案 > 如何用 Jest 和 Enzyme 处理函数中的状态变化

问题描述

我有一个反应组件:

export class Test extends React.Component<TestProps, TestState> {
   ...
   //the constructor sets the state initially
   constructor(props: TestProps) {
      this.state = {
         thisIsAState: 1;
      }
   }
   //this function updates the state given the num param
   updateState(num) {
      this.setState({ thisIsAState: num });
   }

}

所以现在在 jest/enzyme 测试文件中,我有:

/*wrapped in a describe/it...*/

const wrapper = await mount(<Test {..anyPropsHere} />);   
wrapper.instance().updateStates(3);                           //updating the states here via function call
wrapper.update();                                             //tried this to see if it would update anything
expect(wrapper.state().thisIsAState).toEqual(3);              

这不起作用->它将包装器的“状态”变量视为 null - always。即使我在这里直接 setState() ,它也不起作用 - 仍然为空。

我也尝试过 SetTimeout 函数并使用 await,但单元测试似乎跳过了这些:它们完成并通过,但如果我说 .toEqual(4) 期待明显的 1 !== 4 错误,它仍然会通过,所以它是不知何故没有达到这些功能。我也尝试过浅渲染对象。

是否有适当的方法来调用 Test 的更新函数,让它更新状态,然后检查状态?

我在:“酶”:“^3.11.0”,“酶适配器反应 16”:“^1.15.5”,“反应”:“^16.13.1”,

标签: reactjstypescriptasync-awaitjestjsenzyme

解决方案


它应该工作。您不需要调用wrapper.update()方法并使用async/awaitwith mount()

例如

Test.tsx

import React from 'react';

export interface TestProps {}
export interface TestState {
  thisIsAState: number;
}

export class Test extends React.Component<TestProps, TestState> {
  constructor(props: TestProps) {
    super(props);
    this.state = {
      thisIsAState: 1,
    };
  }
  updateState(num) {
    this.setState({ thisIsAState: num });
  }
  render() {
    return <div>{this.state.thisIsAState}</div>;
  }
}

Test.test.tsx

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

describe('66582685', () => {
  it('should pass', () => {
    const wrapper = mount(<Test />);
    // @ts-ignore
    wrapper.instance().updateState(3);
    expect(wrapper.state('thisIsAState')).toEqual(3);
    expect(wrapper.text()).toEqual('3');
  });
});

测试结果:

 PASS  examples/66582685/Test.test.tsx
  66582685
    ✓ should pass (27 ms)

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

包版本:

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

推荐阅读