测试混合 async/Promise-based 代码和基于回调的代码

Testing mixed async/Promise-based code and callback-based code

此代码:

it('should not say overspecified', async function (done) {
    await new Promise(resolve => resolve());
    done();
});

原因:Error: Resolution method is overspecified. Specify a callback *or* return a Promise; not both.

但是...我不会返回 Promise。我只是在等待一个承诺。

如果我将我的代码改成这样,它会起作用:

it('should not say overspecified',function(){
  return new Promise(async resolve=>{
    await (new Promise(resolve=>resolve()));
    resolve();
  })
});

为什么它只在我将代码不必要地包装在 Promise 中时才起作用?

This code:

it('should not say overspecified', async function (done) {
    await new Promise(resolve => resolve());
    done();
});

Causes this: Error: Resolution method is overspecified. Specify a callback or return a Promise; not both.

因为 async functions 总是 return a Promise,设计使然。

在 Mocha 中,您可以 return a Promise 使用 done,但是 not both.

我会这样做:

// Do not pass `done` as a parameter to `it` callback.
it('should not say over specified', function() {
  return new Promise(resolve => resolve())
});

或者如果你想使用 await:

// Do not pass `done` as a parameter to `it` callback.
it('should not say overspecified', async function () {
  await new Promise(resolve => resolve());
});

这是一个实用的async/await例子:

require('chai').should()

const getFoo = async () => 'foo'

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

您应该仅将 done 用于基于回调或基于事件的代码。

完全没有必要将它与基于 Promise 的代码一起使用,例如常规 Promises 或 async/await.

测试基于混合 Promise 和回调的代码:

如果我能控制我正在测试的代码(我写的),我“promisify”我使用的所有基于回调的代码来自外部回调样式 API,所以我正在使用的代码的整个异步 API 始终使用 Promises。如果使用得当,那么它显然也会使测试更容易(通过完全消除 done 的需要)。