code to test
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 gets as far as return user.save() then times out. It seems I am missing something in the unit tests however no error is thrown. I am using sinon-as-promised to resolve the promise but it does not seem to see it.
It looks unlikely that you would have deliberately left out the res.send() call in your sample code for the sake of conciseness.
Just to make sure, are you returning a 200 status code when userCreate function called in the router succeeds?
userCreate(req).then(function() {
// success
res.status(200).send('User created successfully');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With