代码之家  ›  专栏  ›  技术社区  ›  user2151486

在Mocha中使用async/await-测试挂起或最终导致未经处理的承诺拒绝

  •  4
  • user2151486  · 技术社区  · 7 年前

    运行非常简单的测试,其中我在基本授权标头中传递无效凭据,我希望服务器返回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 回调时,测试挂起(名称为红色),显然正在“等待”完成某些操作 enter image description here

    我知道,如果我重写它以使用标准承诺方法,它将起作用。我只是想知道如何通过async/await来实现。

    谢谢

    2 回复  |  直到 7 年前
        1
  •  6
  •   libik    7 年前

    去除 done 从参数(以及函数体),Mocha将期望您返回承诺。

    默认情况下,异步函数返回承诺。

    如果您不抛出错误,它将返回已解决的承诺。

        2
  •  -1
  •   user2347763    7 年前

    更改此代码块

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