用于检查状态更新的测试用例似乎没有给出正确的输出

时间:2018-05-24 17:00:20

标签: javascript reactjs unit-testing jestjs enzyme

我有一个简单的函数,可以在click事件中将组件的状态从true切换为false。 这是功能

public toggleAvailability(dayTime: string): void {
    const isAvailable = this.state[dayTime] === false ? true : false;

    this.setState(
      { [dayTime]: isAvailable }, 
      () => {
      const instructor = {
        userId: this.props.userId,
        availability: this.state.friEarlyAfternoon
      };
      this.props.updateInstructor(instructor);
    });
  }

我正在使用Jest + Enzyme进行单元测试,我正在尝试按如下方式测试我的切换功能:

describe('Method toggleAvailability()', () => {
    function test_toggleAvailability(dayTime: string, currentState: boolean, toggledState: boolean): void {
      beforeEach(() => {
        wrapper.setState({
          dayTime: currentState,
        });
        wrapper.instance().toggleAvailability(dayTime);
      });

      it(`Sets the state's ${dayTime} to ${toggledState}`, () => {
        expect(wrapper.state().dayTime).toEqual(toggledState);
      });
    }
    test_toggleAvailability('monEarlyMorning', false, true);
    test_toggleAvailability('monEMorning', true, false);
  });

出于某种原因,我无法通过测试。我得到这个: enter image description here

有人在这里有建议吗?

1 个答案:

答案 0 :(得分:0)

只要您根据现有状态设置状态,必须使用setState的回调版本以及它传递给您的状态参数,因为state updates are asynchronous and can get batched together

所以这个:

const isAvailable = this.state[dayTime] === false ? true : false;
this.setState(
  { [dayTime]: isAvailable }, 
  () => {
  const instructor = {
    userId: this.props.userId,
    availability: this.state.friEarlyAfternoon
  };
  this.props.updateInstructor(instructor);
});

应该是这样的,你也可以在第一个参数的函数中传递:

this.setState(
  prevState => {
    const isAvailable = prevState[dayTime] === false ? true : false;
    return { [dayTime]: isAvailable };
  },
  () => {
    const instructor = {
      userId: this.props.userId,
      availability: this.state.friEarlyAfternoon
    };
    this.props.updateInstructor(instructor);
  }
);

附注:或者,如果您实际上并不需要=== false上的严格平等,则可以使用!

this.setState(
  prevState => ( { [dayTime]: !prevState[dayTime] } ),
  () => {
    const instructor = {
      userId: this.props.userId,
      availability: this.state.friEarlyAfternoon
    };
    this.props.updateInstructor(instructor);
  }
);