【问题标题】:How to wait for promise in Jest React test?如何在 Jest React 测试中等待承诺?
【发布时间】:2017-09-14 20:07:20
【问题描述】:

我想用 Jest 和 Enzyme 测试一个 React 组件。该组件是一个登录表单,当用户单击登录按钮时,我想根据结果检查对象模型是否已相应更新。

这是用户点击提交按钮时调用的部分代码。

// Login.jsx
handleSubmit(e) {

  var that = this;

  this.setState({stateResult: "", errorLabel: ""});

  if(e) {
    e.preventDefault();
    e.stopPropagation();
  }

  MyService.login(this.state.email, this.state.password).then(function(account) {
    that.setState({stateResult: "login-ok", errorLabel: ""});
  }).catch(function(err) {
    that.setState({stateResult: "login-error", errorLabel: err.data.message});
  });
};

我写了一个 Jest 测试。代码如下:

// Login-test.js
test('that when the signin fails, the stateResult model is updated with login-error', () => {

    const wrapper = shallow(<Landing />);
    wrapper.find('a#landingjsx-signin').simulate('click');

    wrapper.update();
    setTimeout(function() {
        expect(wrapper.state().stateResult).toEqual("login-error");
    }, 100);
});

为了测试它,我使用了 MyService 的模拟

jest.mock('../../../modules/MyService.js');

这是我的模拟代码:

//MyService.js
class MyService {

  constructor() {

  }

  login(user, password) {

    return new Promise((resolve, reject) => {

        process.nextTick(() => {
            if(user === "aaa") {
                resolve({});
            }
            else {
                reject({
                    data: {
                        message: "bad-password"
                    }
                });
            }
        });
    });
  }
}

export default new MyService();

测试失败了 :-)

我的问题是:如何从我的测试中删除 setTimeout() 调用?有没有更好的方法来测试这个基于 Promise 的函数。

我的问题是如何在期待结果之前等待 promise 函数失败?

提前致谢

【问题讨论】:

    标签: javascript reactjs unit-testing promise jestjs


    【解决方案1】:

    只是预感:尝试添加 done 回调。

    // Login-test.js
    test('that when the signin fails, the stateResult model is updated with login-error', (done) => {
    
        const wrapper = shallow(<Landing />);
        wrapper.find('a#landingjsx-signin').simulate('click');
    
        wrapper.update();
        setTimeout(function() {
            try {
              expect(wrapper.state().stateResult).toEqual("login-error");
              done()
            } catch (e) {
              done.fail(e)
            }
        }, 100);
    });
    

    您需要将期望包装在 try-catch 中,因为期望抛出错误并且测试失败将导致 done 不被调用。

    另请参阅 more extended examples 的笑话文档。

    【讨论】:

      猜你喜欢
      • 2021-11-18
      • 2021-02-20
      • 2019-03-11
      • 2016-07-23
      • 2018-10-16
      • 2013-09-16
      • 2020-05-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多