在 Mocha 中使用 async/await - 测试挂起或以未处理的承诺拒绝结束

Usage of async/await in Mocha - test hangs or ends up with unhandled promise rejection

运行 非常简单的测试,我在基本授权 header 中传递无效凭据,我希望服务器 return 401

const request = require('request-promise');
const expect = require('chai').expect;
const basicToken = require('basic-auth-token');

describe('PUT Endpoint', function () {
 it.only('should return unauthorized if basic token is incorrect', async function (done) {
                let options = {
                    url: `http://url_to_handle_request`,
                    resolveWithFullResponse: true,
                    headers: {
                        Authorization: `Basic ${basicToken('INVALID', 'CREDENTIALS')}`
                    }
                };

                try {
                    await request.put(options); // this should throw exception
                } catch (err) {
                    expect(err.statusCode).to.be.equal(401); // this is called
                }
                done();
            });
});

此代码的问题在于 expect 子句解析为 false(因为服务器响应例如 403)并且测试以错误结束:

UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): AssertionError: expected 403 to equal 401

如果我省略 done 回调,测试就会挂起(名称为红色)并且显然 "waiting" 需要完成一些事情

我知道如果我将它重写为使用标准的承诺方法,它会起作用。我只是好奇如何通过 async/await.

谢谢

从参数(以及函数体)中删除 done,然后 Mocha 将期望您 return Promise。

异步函数 return默认承诺。

如果您不抛出错误,它 return 已解决 promise。

更改此代码块

try {
                    await request.put(options); // this should throw exception
                } catch (err) {
                    expect(err.statusCode).to.be.equal(401); // this is called
                }
                done();

                await request.put(options)
                    .then(()=>{ })
                    .catch(function (err)){ 
                      expect(err.statusCode).to.be.equal(401);
                     }