0

I am using supertest, mocha and expect for testing my app. I encountered an issue where the document returned is null and there is no error.

router.get('/user', function (req, res) {
    User.findOne({
        _id: '56c59bb07a42e02d11a969ae'
    }, function (err, user) {

       if(err) return res.status(404).json({message: 'not found: ' + err.message});

        res.status(200).json(user);
    });
});

When I test this on Postman I always get 200 which is what I expected but when I run the test I get 404 :(

My simple test code below where I always get the 404.

it('get user', function (done) {
        request(app)
            .get('/user')
            .expect(200)
            .end(function (err, res) {

                if (err) throw err;
                done();
            });
});

Both Postman and the test are referring to the same mongoose database so I'm sure that it should be able to fetch the user. How mongoose and the app are setup in my server below.

mongoose.connect('mongodb://localhost/scratch', options);

app.listen(port, function () {
    console.log('Scratch started on port ' + port);
});

Is there something I need to do to make it work?

naz
  • 1,478
  • 2
  • 21
  • 32

1 Answers1

0

I modified the test a bit where the User is created on 'before'.

before(function (done) {
            connection.on('error', console.error);
            connection.once('open', function () {
                done();
            });
            mongoose.connect(config.db[process.env.NODE_ENV]);

            var userInfo = {
                "username": "naz2@gmail.com",
                "password" : "123456",
                "nickname": "naz"
            }

            var newUser = User(userInfo);

            newUser.save(function (err, doc) {
                if(err) {
                     console.log('err: ' + err.message);
                } else{
                     console.log('saved');
                }

            })

            console.log(mongoose.connection.readyState);
            done();
        });

Then ran the same test and it worked!

My guess is that during the test the app is querying against documents in memory( I verified that by checking the db and the new user was not added) and not to an existing document like I was expecting when testing with Postman. Which means I need to seed the test db first before I can use it for the test.

I am new to Nodejs and I'm curious to what caused the documents to be created in memory and how mongoose/express know that it is ran by a test/supertest and behave accordingly.

naz
  • 1,478
  • 2
  • 21
  • 32