【问题标题】:A more elegant way to test time passing in mocha一种更优雅的方式来测试摩卡的时间传递
【发布时间】:2017-06-30 12:54:09
【问题描述】:

我最近不得不修复一个在工作中使用旧的 react 组件的错误。通常在修复错误时,我们会用它编写测试。问题是,react 组件从服务器异步获取(我可以重构代码,以便将异步操作移动到 redux 中,但我们不将重构作为错误修复的一部分)所以在测试组件是什么时应该渲染,我必须等待500ms 才能让承诺解决。

我知道如果我创建组件的实例并直接调用该方法,我就不必执行 setTimeout,我可以只执行 .then,但我们喜欢测试组件的输入/输出而不调用内部方法。

有没有比设置超时更优雅的解决方案?这是当前代码:

it('autofills and locks all the fields where user data is present', function(done) {
    const emailInput = $wrapper.find('#email');
    emailInput.value = 'email@example.com';
    emailInput.simulate('blur');

    // - autofill does an async request
    // - we need to wait for the promise to resolve before
    //   checking if the inputs are disabled or not
    setTimeout(() => {
      const identifierInput = $wrapper.find('#id');
      const lastNameInput = $wrapper.find('#last-name');
      const phoneNumberInput = $wrapper.find('#phone-number');
      const firstNameInput = $wrapper.find('#first-name');

      expect(firstNameInput.html().includes('disabled')).to.be.true;
      expect(lastNameInput.html().includes('disabled')).to.be.true;
      expect(phoneNumberInput.html().includes('disabled')).to.be.true;
      expect(identifierInput.html().includes('disabled')).to.be.true;
      done();
    }, 500);
});

【问题讨论】:

    标签: javascript mocha.js enzyme


    【解决方案1】:

    “我们不将重构作为错误修复的一部分”...哇。

    无论如何,如果您需要编写测试来完成您的工作,您将需要模拟您的 API 调用。只要网络有点慢或者其他什么时候,500ms 超时就会失败,这是一个非常非常非常脆弱的测试。

    由于您没有详细说明请求是如何发出的,我无法告诉您其他任何信息,但是您会发现所有 HTTP 请求风格的模拟库:fetch-mock 用于 fetch、nock... 有很多.

    这个想法是您应该预先设置一个虚假的答案并立即返回(如果需要,使用 Promise.resolve())。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-04
      • 2017-08-27
      • 1970-01-01
      • 1970-01-01
      • 2015-08-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多