I'm using supertest, chai and mocha to test my Web API application. 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:
// 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);
and sends the error as the response of the API. I would like to catch the deferred.reject(e);
part and in the same time continue the chain of .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. Also I can't chai's expect().to.throw()
because there is not exception being thrown.
Disclaimer: I never use deferred.reject().
Possible solution: use sinon .
You can use spy , if you want the real deferred.reject() to run and you just want to monitor it. 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.
Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.