deep-eql algorithm does not perform deep equality checks on errors. For more information, visit this link.
To address this issue, here is the proposed solution:
index.js
:
const CustomError = require('./customError');
const controller = {
async getUser(req, res, next) {
try {
if (!req.user) {
throw new CustomError('User not found', 404);
} else {
// perform actions
}
} catch (err) {
next(err);
}
},
};
module.exports = controller;
customError.js
:
class CustomError extends Error {
constructor(message, code) {
super(message);
this.code = code;
}
}
module.exports = CustomError;
index.test.js
:
const controller = require('./');
const CustomError = require('./customError');
const sinon = require('sinon');
const { expect } = require('chai');
describe('61879445', () => {
it('should throw error if user not found', async () => {
const mNext = sinon.stub();
const mReq = {};
const mRes = {};
await controller.getUser(mReq, mRes, mNext);
// Using Chai assertions
expect(mNext.getCall(0).args[0]).to.be.an.instanceof(CustomError);
expect(mNext.getCall(0).args[0]).to.have.property('message', 'User not found');
expect(mNext.getCall(0).args[0]).to.have.property('code', 404);
// Using Sinon assertions
sinon.assert.calledWith(
mNext,
sinon.match
.instanceOf(CustomError)
.and(sinon.match.has('message', 'User not found'))
.and(sinon.match.has('code', 404)),
);
});
});
Unit test results along with coverage report:
61879445
✓ should throw error if user not found
1 passing (15ms)
----------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------------|---------|----------|---------|---------|-------------------
All files | 100 | 50 | 100 | 100 |
customError.js | 100 | 100 | 100 | 100 |
index.js | 100 | 50 | 100 | 100 | 6
----------------|---------|----------|---------|---------|-------------------