Mocha测试是否Http Request Promise抛出:未处理的承诺拒绝

时间:2017-10-05 13:14:17

标签: javascript typescript mocha chai superagent

我正在尝试测试我的Http Request方法是否会抛出错误,但我总是得到:未处理的承诺拒绝

这是我的测试:

"desiredCapabilities": {
        "browserName": "chrome",
        "chromeOptions": {
          "args": ["--lang=en-GB"],
          "prefs": {
            "intl": {
              "accept_languages": "en-GB"
            }
          }
        }
      }

这是我的方法(“Offeree”会导致错误):

    it('it should get the first page of all offers with limit 20 without a cache system', (done) => {
        const httpRequestConnector = new HttpRequestConnector(apiConfigs);
        const queryArgs: any = {
            page: 1,
            limit: 20,
        };

        const functionThatThrows = () => {
            httpRequestConnector.offersFindAll(queryArgs, 'admin').then((res) => {
                res.should.have.property('status');
                res.status.should.equal(200);
                res.should.have.property('body');

                res.body.should.have.property('request');
                res.body.request.should.have.property('page');
                res.body.request.page.should.equal('1');
                res.body.request.should.have.property('limit');
                res.body.request.limit.should.equal('20');

                res.body.should.have.property('response');
                res.body.response.should.have.property('data');
                res.body.response.data.should.have.property('data');

                Object.keys(res.body.response.data.data).length.should.equal(20);
            }).catch((err) => {
                throw err;
            });
        };

        expect(functionThatThrows).to.throw();
        done();
    });

这是我的HttpRequestService的POST方法:

...
private query(url: string, send: any): Promise<any> {
    const httpRequestService: HttpRequestInterface = new HttpRequestService();

    return httpRequestService.post({
        url,
        send,
    });
}

offersFindAll(args: any, apiDefinition: string): Promise<any> {
    (new GuardAgainstNullValues())
        .guard(apiDefinition);

    const queryArgs = args || {};
    const target: string = (apiDefinition === 'admin') ? 'Offeree' : 'Affiliate_Offer';
    const method: string = 'findAll';
    const apiInfos: any = this.getApiInfos(apiDefinition);
    const url: string = apiInfos.api + '?api_key=' + apiInfos.api_key + '&Target=' + target + '&Method=' + method;

    if (queryArgs && 'limit' in queryArgs) {
        queryArgs.limit = args.limit;
    } else {
        queryArgs.limit = 1000;
    }

    return new Promise((fulfill, reject) => {
        return this.query(url, queryArgs)
            .then((res) => {
                if (res.body.response.status === -1) {
                    throw new RequestStatusException('Cannot get offers');
                }

                fulfill(res);
            })
            .catch((err) => {
                reject(err);
            });
    });
}
...

我将offersFindAll请求包含在处理class HttpRequestService implements HttpRequestInterface{ private engine: SuperAgentStatic; constructor() { this.engine = request; // Superagent } get({ url, query }: { url: string, query?: any }): Promise<any>{ return new Promise((fulfill: any, reject: any) => { this.engine .get(url) .query(query) .end((err: ResponseError, res: Response) => { if (err) { reject(err); } fulfill(res); }); }); } post({ url, send }: { url: string, send?: any }): Promise<any>{ return new Promise((fulfill: any, reject: any) => { this.engine .post(url) .send(qs.stringify(send)) .end((err: ResponseError, res: Response) => { if (err) { reject(err); } fulfill(res); }); }); } }; 的承诺中,以便在我使用此方法的任何地方抛出错误而不是抛出错误。

我试图期望函数在我的mocha测试中抛出:if (res.body.response.status === -1) {

但我总是得到一个expect(functionThatThrows).to.throw();,这是一个很好的例外,但我无法正确处理这个承诺。

我尝试仅返回(node:7485) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): RequestStatusException: Cannot get offers而不将其包含在承诺中,但也是如此。

如何正确地构造它以测试它是否会抛出?

非常感谢您的帮助

1 个答案:

答案 0 :(得分:0)

在你的方法offersFindAll():

    return new Promise((fulfill, reject) => {
    return this.query(url, queryArgs)
        .then((res) => {
            if (res.body.response.status === -1) {
                throw new RequestStatusException('Cannot get offers');
            }

            fulfill(res);
        })
        .catch((err) => {
            reject(err);
        });
});

catch子句无法捕获异常。写这样更好:

    return new Promise((fulfill, reject) => {
    return this.query(url, queryArgs)
        .then((res) => {
            if (res.body.response.status === -1) {
                reject('Cannot get offers');
            }

            fulfill(res);
        })
        .catch((err) => {
            reject(err);
        });
});

同时,可以使用以下命令找到错误的堆栈跟踪:

process.on('unhandledRejection', (reason, p) => {
  console.log('Unhandled Rejection at:', p, 'reason:', reason);
  // application specific logging, throwing an error, or other logic here
});