I am new to the NodeJS and seeking some advice on what would be the best approach on how to unit test a method in my controller.
Here's the method of my controller I want to test:
getAll: function(req, res, next) {
let pageNum = parseInt(req.query.pageNum, 10) || 0,
pageSize = parseInt(req.query.pageSize, 10) || 500,
orderBy = req.query.orderBy && req.query.orderBy.split(",");
return Tenant
.query()
.orderByAll(orderBy)
.page(pageNum, pageSize)
.then(results => {
res.json(Object.assign(results, { pageNum, pageSize }));
})
.catch(next);
}
And here's my current test I wrote but is not working:
describe('Test getting all tenants without getting error', () => {
it('body in res object should not be empty, and http status should be 200', () => {
tracker.on('query', function checkResult(query) {
query.response([{
"id": "6790ac7c-24ac-4f98-8464-42f6d98a53ae",
"name": "astar",
"publicKey": "this is a test"
},
{
"id": "7790ac7c-24ac-4f98-8464-42f6d98a53ae",
"name": "bstar",
"publicKey": "this is a test"
}]);
});
tenantController.getAll(req, res, next).then(function() {
console.log('Hello');
expect(res.statusCode).to.equal(400);
expect(JSON.parse(res._getData()).id).to.equal("shaflh;sahfl;s");
}).catch(e => {
console.log(e);
})
});
});
As you can see the method getAll returns a promise. I'm using knex and objectionjs for modelling and querying database (Postgresql). In my test i try to mock what I expect knex to return (using mock-knex), which is:
query.response([{
"id": "6790ac7c-24ac-4f98-8464-42f6d98a53ae",
"name": "astar",
"publicKey": "this is a test"
},
{
"id": "7790ac7c-24ac-4f98-8464-42f6d98a53ae",
"name": "bstar",
"publicKey": "this is a test"
}]);
And it's not working, because I purposely put in code to print some thing out to the console and it doesn't print anything out at this moment:
tenantController.getAll(req, res, next).then(function() {
console.log('Hello');
expect(res.statusCode).to.equal(400);
expect(JSON.parse(res._getData()).id).to.equal("shaflh;sahfl;s");
})
At this point I would expect my promise would get rejected, but then nothing happens too in my catch:
catch(e => {
console.log(e);
})
My questions now would be: 1) In general, what would be a right thing to test for this getAll function. Right now, I'm testing if res object is updated with correct data, but not sure if it's a good way to test this function. 2) Is mocking a good approach in this situation? I'm trying to look for tutorials on mocking but it seems like testing with a real database is more popular in NodeJS world.
Aucun commentaire:
Enregistrer un commentaire