【问题标题】:Test asynchronous async await JavaScript function测试异步 async await JavaScript 函数
【发布时间】:2017-10-15 19:58:17
【问题描述】:

我编写了一个异步 JavaScript 函数,但似乎没有得到我期望的返回值。如果我误解了异步函数的工作原理,或者我的测试不太正确,有人可以解释一下吗?

下面是我的测试,使用 Nock 模拟了一个服务。

it('Should call async validation function when button is clicked', () => {
    const request = nock(/.*/)
      .get('/my-service/logincodes/abc123')
      .reply(404);

    const comp = mount(
      <LoginCodeView />
    );
    expect(comp.instance().doesLoginCodeExist('abc123')).to.equal('Your Login code is not recognized.');
 });

以及被测函数:

  doesLoginCodeExist = async (loginCode) => {
    if (loginCode.match(loginPattern)) {
      const response = await MyService.getUserByLoginCode(loginCode);

      if (response.code) {
        return {};
      } else if (response.status === 404) {
        return { error: 'Your login code is not recognized.', success: null };
      }
      return { error: 'Service is temporarily unavailable.', success: null };
    }
    return null;
  };

我已经注销了代码所采用的路径,并且它似乎确实按预期进入了 else if 分支,但是我总是得到一个空对象 {} 返回,而不是像预期的那样具有错误和成功属性的对象?

【问题讨论】:

  • async 函数总是返回一个Promise 对象。我怀疑这就是你所说的空对象。您可以尝试将您的测试功能设为async 并在那里使用await
  • 感谢@AlexanderO'Mara 让我的测试异步等待很有用。

标签: javascript reactjs asynchronous async-await nock


【解决方案1】:

async 函数始终返回 Promise 对象。我怀疑这就是你所说的空对象。

作为一种解决方案,您可以尝试将您的测试功能设为async 并在那里也使用await。然后你可以测试 promise 解析到的值。

【讨论】:

    【解决方案2】:

    让我的测试异步等待解决了这个问题。

    it('Should call async validation function when button is clicked', async () => {
        const request = nock(/.*/)
          .get('/my-service/logincodes/abc123')
          .reply(404);
    
        const comp = mount(
          <LoginCodeView />
        );
        const returned = await comp.instance().doesLoginCodeExist('abc123')
        expect(returned.error).to.equal('Your Login code is not recognized.');
     });
    

    【讨论】:

      猜你喜欢
      • 2019-07-24
      • 1970-01-01
      • 1970-01-01
      • 2019-05-12
      • 1970-01-01
      • 1970-01-01
      • 2018-08-21
      • 2020-09-02
      • 2020-01-31
      相关资源
      最近更新 更多