Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Test function that returns Mongoose promise

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.

like image 679
mattwilsn Avatar asked Oct 31 '22 02:10

mattwilsn


1 Answers

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');
}
like image 110
Arun N. Kutty Avatar answered Nov 15 '22 05:11

Arun N. Kutty