如何使用 await 使用 mocha 测试异步代码 [英] How to test async code with mocha using await

查看:108
本文介绍了如何使用 await 使用 mocha 测试异步代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 mocha 测试异步代码?我想在 mocha

How do I test async code with mocha? I wanna use multiple await inside mocha

var assert = require('assert');

async function callAsync1() {
  // async stuff
}

async function callAsync2() {
  return true;
}

describe('test', function () {
  it('should resolve', async (done) => {
      await callAsync1();
      let res = await callAsync2();
      assert.equal(res, true);
      done();
      });
});

这会产生以下错误:

  1) test
       should resolve:
     Error: Resolution method is overspecified. Specify a callback *or* return a Promise; not both.
      at Context.it (test.js:8:4)

如果我删除 done() 我得到:

If I remove done() I get:

  1) test
       should resolve:
     Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/tmp/test/test.js)

推荐答案

你可以返回 Promise:

Mocha 支持 Promises 开箱即用;你只需要return Promise 给it().如果解决,则测试通过,否则失败.

You can return the Promise:

Mocha supports Promises out-of-the-box; You just have to return the Promise to it(). If it resolves then the test passes otherwise it fails.

由于 async 函数总是隐式返回一个 Promise 你可以这样做:

Since async functions always implicitly return a Promise you can just do:

async function getFoo() {
  return 'foo'
}

describe('#getFoo', () => {
  it('resolves with foo', () => {
    return getFoo().then(result => {
      assert.equal(result, 'foo')
    })
  })
})

您的 it 不需要 doneasync.

You don't need done nor async for your it.

async function getFoo() {
  return 'foo'
}

describe('#getFoo', () => {
  it('returns foo', async () => {
    const result = await getFoo()
    assert.equal(result, 'foo')
  })
})

在任何一种情况下,不要done 声明为参数

如果您使用上述任何方法,则需要从代码中完全删除 done.将 done 作为参数传递给 it() 提示 Mocha 您打算最终调用它.

In either case, do not declare done as an argument

If you use any of the methods described above you need to remove done completely from your code. Passing done as an argument to it() hints to Mocha that you intent to eventually call it.

done 方法仅用于测试基于回调或基于事件的代码.

The done method is only used for testing callback-based or event-based code.

这篇关于如何使用 await 使用 mocha 测试异步代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆