How to test async code with mocha using await

大憨熊 提交于 2021-02-17 15:12:17

问题


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();
      });
});

This produces error below:

  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)

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)

回答1:


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.

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')
    })
  })
})

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

If you still insist on using async/await:

async function getFoo() {
  return 'foo'
}

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

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.

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



来源:https://stackoverflow.com/questions/52641469/how-to-test-async-code-with-mocha-using-await

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!