0

I have an express route in a Node application that uses Mongoose for querying a Mongo database. There is a promise used in the get request to find items and I am not sure how to test this promise.

I am not very familiar with unit testing node applications.

Here is the code for the express route, this works but I am not sure how to test it:

var express = require('express');
var router = express.Router();
var promise = require('bluebird');
// bluebird.promisifyAll is used on Mongoose in app.js
var ItemModel = require('./itemModel');

router.get('/', function(req, res, next) {
    ItemModel.findAsync()
        .then(function(items) {
            res.status(200).send(items);
        })
        .catch(function(err) {
            next(err);
        });

});

module.exports = router;

Here is what I have stubbed out in the test so far. I am not sure how to test the promise in the routes.get method :

describe('ItemRoute', function() {
    var express = require('express');
    var bodyParser = require('bodyParser');
    var supertest = require('supertest');
    var sinon = require('sinon');
    var expect = require('chai').expect;
    var assert = require('chai').assert;

    var ItemModel = require('./ItemModel');
    var ItemRoute = require('ItemRoute');

    var uri = '/items/';

    var agent;

    beforeEach(function(done) {
        var app = express();

        app.use(bodyParser.json());
        app.use(bodyParser.urlencoded({extended: false}));
        app.use(uri, releaseNotesRoute);

        agent = supertest.agent(app);

        done();
    });

    describe('GET', function() {
        it('returns an empty array when no items are stored in Mongo', function() {

            // Not sure how to test the route here with a get that
            // uses a promise, ItemModel.findAsync().then

        });
    });

});
1

1 Answer 1

2

to able to use promises in test, you should have to install sinon-as-promises module from npm. Then you can mock ItemModel like this:

var itemModelMock = sinon.mock(ItemModel);
itemModelMock.expects('findAsync').resolves([]);
2
  • Is itemModelMock.expects('findAsync').resolves([]) the expected return from the ItemModel.findAsync.then() call?
    – Mdd
    Feb 10, 2016 at 21:58
  • Yes, resolves use for then, itemModelMock.expect('findAsync').rejects() use for catch
    – PatBusz
    Feb 11, 2016 at 9:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.