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

Javascript 检查状态更新的测试用例不';似乎没有给出正确的输出,javascript,reactjs,unit-testing,jestjs,enzyme,Javascript,Reactjs,Unit Testing,Jestjs,Enzyme,我有一个简单的函数,可以在单击事件中将组件的状态从true切换到false。 这里是函数 public toggleAvailability(dayTime: string): void { const isAvailable = this.state[dayTime] === false ? true : false; this.setState( { [dayTime]: isAvailable }, () => { const

我有一个简单的函数,可以在单击事件中将组件的状态从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+Ezyme进行单元测试,并尝试按如下方式测试切换功能:

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);
  });
由于某种原因,我无法通过考试。我明白了:


有人在这里有什么建议吗?

每当您根据现有状态设置状态时,必须使用
setState
的回调版本及其传递给您的state参数,因为

因此:

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);
  }
);

我猜,写
const isAvailable=this.state[daily]==false?真:假;这个.setState({[Daily]:isAvailable},
或使用函数setState是一回事,因为OP实际上并没有改变状态。问题在于测试case@ShubhamKhatri:newFlagHereBasedOnState
不是变异状态吗?测试用例也可能有缺陷(我不使用讨论中的工具,不能说;如果你这么说,我相信你:-),但是这里需要
setState
的回调版本。