I'm trying to test app in NodeJS. For tests I'm using MochaJS, sinon, sinon-mongoose, sinon-as-promised and ShouldJS. I wrote a test and I had a problem with mock. Situation does look like this: API:
app.post('/api/admin/content', function (req, res) {
var contents = [];
var promise1 = new Promise(function(resolves, rejects){
content.find().exec(function(err, contentRecord){
if (err) return rejects();
return resolves(contentRecord);
})
}).then(function(data){
contents.push(data);
});
...
add here adding a new content
...
var promise2 = new Promise(function(resolves, rejects){
content.find().exec(function(err, contentRecord){
if (err) return rejects();
return resolves(contentRecord);
})
}).then(function(data){
contents.push(data);
});
Promise.all([promise1, promise2]).then(function(){
if (contents.length > 1) {
return res.send(contents);
} else {
return res.status(400).send();
}
});
});
TEST:
describe('/routes/admin/content', function () {
it('get_all_contents', function(done){
contentMock.expects('find').chain('exec').withArgs(sinon.match.any).yields(null, [{"L":1}]);
request(server)
.json()
.base('http://localhost:8889')
.post('/api/admin/content')
.expectStatus(200)
.end(function (err, req, body) {
if (err) throw err;
body.should.not.be.empty();
done();
});
})
});
While the first Promise is working as expected, the second one, simply fails (there is an error with exceeding time). I even found a solution for this (though it is hardly a solution), and its about removing this line:
contentMock.expects('find').chain('exec').withArgs(sinon.match.any).yields(null, [{"L":1}]);
The problem only occurs in test, while application works pretty fine with that api as it is.
How to properly write a mock over here? Cause I'm expecting that to be the case.
Aucun commentaire:
Enregistrer un commentaire