【问题标题】:Test case to check state update doesn't seem to be giving a correct output检查状态更新的测试用例似乎没有给出正确的输出
【发布时间】:2018-12-14 00:30:27
【问题描述】:

我有一个简单的函数,可以在单击事件时将组件的状态从 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);
  });

由于某种原因,我无法通过测试。我得到这个:

这里有人有建议吗?

【问题讨论】:

    标签: javascript reactjs unit-testing jestjs enzyme


    【解决方案1】:

    任何时候您根据现有状态设置状态,您必须使用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);
      }
    );
    

    【讨论】:

    • 我猜,写 const isAvailable = this.state[dayTime] === false ? true : false; this.setState( { [dayTime]: isAvailable }, 或使用函数 setState 是一回事,因为 OP 实际上并没有改变状态。问题出在测试用例上
    • @ShubhamKhatri:[dayTime]: newFlagHereBasedOnState 怎么没有变异状态?测试用例可能也有缺陷(我没有使用有问题的工具,不能说;如果你这么说,我相信你:-)),但@987654330的回调版本此处需要@。
    猜你喜欢
    • 2019-06-14
    • 2018-03-29
    • 1970-01-01
    • 2018-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-14
    相关资源
    最近更新 更多