Unit Test function that returns a Mongoose promise

for check

import { User } from '../models/no-sql/user'; function userCreate(req) { const user = new User({ username: req.username, password: req.password }); return user.save(); } app.get('/userCreate', function(req, res) { User.findOne({ username: req.username }).lean().exec((err, data) => { if(data){ userCreate(req).then(function() { // success }, function(err) { // error }); }else{ // no user found } }); }); 

unit test

  require('sinon-as-promised'); import request from 'supertest'; const user = { username: newUserName, password: 'password' }; factory.build('user', user, function(err, userDocument) { UserMock. expects('findOne').withArgs(sinon.match.any) .chain('lean') .chain('exec') .yields( null, undefined); const docMock = sinon.mock(userDocument); docMock.expects('save') .resolves([]); request(app) .post('/userCreate') .send({username: newUserName, password: 'password') .expect(200) .end((err, res) => { if(err) done(err); should.not.exist(err); should.equal(res.body.success, true); done(); }); }); 

the test comes to the return of user.save (), then the time runs out. It seems that I am missing something in unit tests, but the error does not occur. I use sinon, as I promised to resolve the promise, but does not seem to see it.

+5
source share
1 answer

It seems unlikely that you intentionally refused to call res.send () in your code example for the sake of brevity.

Just to make sure you return a 200 status code when the userCreate function called on the router succeeds?

 userCreate(req).then(function() { // success res.status(200).send('User created successfully'); } 
+2
source

All Articles