简体   繁体   English

如何使用 supertest 和 chai 捕获 deferred.reject?

[英]How to catch deferred.reject using supertest and chai?

I'm using supertest, chai and mocha to test my Web API application.我正在使用 supertest、chai 和 mocha 来测试我的 Web API 应用程序。 I have the following code:我有以下代码:

it('should return 500', function(done) {
    this.timeout(30000);
    request(server)
        .get('/some/path')
        .expect(500)
        .end(function(err, res) {
            done();
        });
});

It should fail.它应该失败。 The code which runs in the get request is:get请求中运行的代码是:

        // Inside method getData
        try {
            // Get data
            // throws error
        } catch (e) {
            // catches error and displays it
            deferred.reject(e);
            return deferred.promise;
        }

    // Other code not in getData method
    dbOps.params.getData(collection, parameter, query).then(
         function (arr) {
            response.send(arr);
         }, function (err) {
            logger.error(err.message);
            response.status(500).send(err.message);
         }
    );

It basically does deferred.reject(e);它基本上是deferred.reject(e); and sends the error as the response of the API.并将错误作为 API 的响应发送。 I would like to catch the deferred.reject(e);我想赶上deferred.reject(e); part and in the same time continue the chain of .except(500).end(...).部分并同时继续.except(500).end(...). Something like:就像是:

catch_deferred(request(server).get('/some/path'))
        .expect(500)
        .end(function(err, res) {
            expect(err).to.equal(null);
            expect(res.body).to.be.an('object').that.is.empty;
            done();

Is there some way to do it?有什么办法吗? I can't use the try-catch block because its not an exception.我不能使用 try-catch 块,因为它不是例外。 Also I can't chai's expect().to.throw() because there is not exception being thrown.我也不能 chai 的expect().to.throw()因为没有抛出异常。

Disclaimer: I never use deferred.reject().免责声明:我从不使用 deferred.reject()。

Possible solution: use sinon .可能的解决方案:使用sinon

You can use spy , if you want the real deferred.reject() to run and you just want to monitor it.如果您希望真正的 deferred.reject()运行并且您只想监视它,您可以使用spy Monitor means: to know whether the method get called, with what argument, and also the return value.监控的意思是:知道方法是否被调用,使用什么参数,以及返回值。 Example:例子:

// Preparation: (Disclaimer: I never use Deferred.reject())
const spyDeferredReject = sinon.spy(Deferred, 'reject');
// Do stuff..
// Expectation phase: check whether deferred reject get called.
expect(spyDeferredReject.calledOnce).to.equal(true);
// Check whether deferred reject called with correct argument.
expect(spyDeferredReject.args[0][0]).to.be.an('error');

You can use stub , if you want to monitor it and make sure the real method not get called.如果要监视它并确保调用真正的方法,可以使用stub

Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM