【问题标题】:How to test a handler containing setState如何测试包含 setState 的处理程序
【发布时间】:2019-05-21 13:20:50
【问题描述】:

我有一个组件ButtonTest.js

import React from 'react';
class ButtonTest extends React.Component {
  constructor() {
    super();
    this.state = {
      disabled: false,
    };
  }

  handleClick = () => {
    this.setState({
      disabled: !this.state.disabled,
    });
  }

  render() {
    return (
      <div>
        <button onClick={this.handleClick}>
          First Button
        </button>
        <button disabled={this.state.disabled}>
          Second Button
        </button>
      </div>
    );
  }
}

export default ButtonTest;

文件ButtonTest.test.js中的测试代码

import React from 'react';
import Enzyme, { shallow, mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import ButtonTest from "./ButtonTest";

Enzyme.configure({ adapter: new Adapter()});

describe('<Button />', () => {
  it('test buttontest', () => {
    const wrapper = shallow(<ButtonTest />);
    const firstButton = wrapper.find('button').at(0);
    const secondButton = wrapper.find('button').at(1); 

    firstButton.props().onClick();
    expect(secondButton.props().disabled).toEqual(true);
  });
});

firstButton.props().onClick(); 将触发handleClick,然后调用setState。但是,setState 是一个异步函数,所以断言会在render 之前被调用。这就是测试失败的原因。

如何确保render 在调用断言之前完成

【问题讨论】:

    标签: reactjs unit-testing jestjs enzyme


    【解决方案1】:

    我像这样更新测试代码。我一开始没有定义secondButton,点击完成后定义

    describe('<Button />', () => {
      it('test buttontest', () => {
        const wrapper = shallow(<ButtonTest />);
        const firstButton = wrapper.find('button').at(0);
        firstButton.props().onClick();
        const secondButton = wrapper.find('button').at(1);
    
        expect(secondButton.props().disabled).toEqual(true);
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-30
      • 1970-01-01
      • 2022-08-18
      • 2017-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多