I have following express-validator middleware code to test
//validator.js
const {body, validationResult, param} = require('express-validator/check');
exports.anyValidator = [
body('first_body')
.exists()
.withMessage('any error message'),
body('second_body')
.exists()
.withMessage('any error message'),
body('third_body')
.exists()
.withMessage('any error message'),
function(req, res, next) {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({errors: errors.mapped()});
}
next();
},
];
The example uses of validator in router
//router.js
const router = require('express').Router();
const vld = require('../middlewares/validator');
const url = './path
router.post(url, vld.anyValidator, (req, res) => {
res.status(201)
});
I have tried to create the test code (using Jest) by accessing directly the 'anyValidator' middleware. But the test didn't work. The test always return 'next()' although I send the empty body (it should return res.status(422)).
What would the best way to unit test the express-validator middleware above (validator.js)?
The test code
//validator.unit.test.js
const httpMocks = require('node-mocks-http');
const sinon = require('sinon');
const vld = require('../analytics');
describe('Testing validator', () => {
describe('anyValidator test', () => {
let reqMocks;
let resMocks;
let nextMocks;
beforeEach(() => {
reqMocks = httpMocks.createRequest({body: {}});
resMocks = httpMocks.createResponse();
nextMocks = sinon.spy();
});
it('Test', async (done) => {
await vld.anyValidator[3](reqMocks, resMocks, nextMocks);
console.log(nextMocks.calledOnce); //it should return false
done();
});
});
});
Note: vld.anyValidator[3] means to access the function(req, res, next) in validator which is the third element.
Thank you for all help. I've solved the problem. I realized that I just need to test all the objects of validator exclude function(req, res, next). After that, we run the last object of validator that is function(req, res, next) with parameter req and res from the previous test of all validator objects.
Below is the code of the solution:
const validatorTester = async (validatorArr, mockReq, mockRes, mockNext) => {
const next = jest.fn();
for (let i = 0; i < validatorArr.length - 1; i++) {
await validatorArr[i](mockReq, mockRes, next);
}
await validatorArr[validatorArr.length - 1](mockReq, mockRes, mockNext);
return [mockReq, mockRes, mockNext];
};
Note: I use Jest as testing framework.
If there is any better solution, let comment my answer or answer the question. Thank you