我在Node应用程序中有一个使用Mongoose查询Mongo数据库的快速路由。 get
请求中有一个承诺用于查找项目,我不确定如何测试此承诺。
我对单元测试节点应用程序不是很熟悉。
以下是快速路线的代码,这有效,但我不知道如何测试它:
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;
到目前为止,这是我在测试中剔除的内容。我不确定如何在routes.get方法中测试promise:
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
});
});
});
答案 0 :(得分:1)
为了能够在测试中使用promises,你必须从npm安装sinon-as-promises模块。然后你可以像这样模拟ItemModel:
var itemModelMock = sinon.mock(ItemModel);
itemModelMock.expects('findAsync').resolves([]);