Reputation: 4400
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
});
});
});
Upvotes: 0
Views: 561
Reputation: 46
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([]);
Upvotes: 2