在使用 Node.js (CompoundJS + PassportJS) 构建的应用程序中,如何在锁定并需要登录的控制器上运行 Mocha 测试?我曾尝试使用 Superagent,但运气不佳,要使用它,服务器需要运行才能运行测试。我已经非常接近这种方法,但不想让服务器运行来运行单元测试。
我还尝试了包括护照和使用request.login
方法,最终我一直收到错误passport.initialize()
中间件未使用。
我试图坚持使用生成的 CompoundJS 测试,这些测试在涉及身份验证之前工作得很好。默认的 CompoundJS 测试运行一个init.js
文件,该文件可以很好地处理身份验证,并以某种方式提供给每个控制器测试:
require('should');
global.getApp = function(done) {
var app = require('compound').createServer()
app.renderedViews = [];
app.flashedMessages = {};
// Monkeypatch app#render so that it exposes the rendered view files
app._render = app.render;
app.render = function(viewName, opts, fn) {
app.renderedViews.push(viewName);
// Deep-copy flash messages
var flashes = opts.request.session.flash;
for (var type in flashes) {
app.flashedMessages[type] = [];
for (var i in flashes[type]) {
app.flashedMessages[type].push(flashes[type][i]);
}
}
return app._render.apply(this, arguments);
}
// Check whether a view has been rendered
app.didRender = function(viewRegex) {
var didRender = false;
app.renderedViews.forEach(function(renderedView) {
if (renderedView.match(viewRegex)) {
didRender = true;
}
});
return didRender;
}
// Check whether a flash has been called
app.didFlash = function(type) {
return !!(app.flashedMessages[type]);
}
return app;
};
控制器/users_controller_test.js
var app,
compound,
request = require('supertest'),
sinon = require('sinon');
/**
* TODO: User CREATION and EDITs should be tested, with PASSPORT
* functionality.
*/
function UserStub() {
return {
displayName: '',
email: ''
};
}
describe('UserController', function() {
beforeEach(function(done) {
app = getApp();
compound = app.compound;
compound.on('ready', function() {
done();
});
});
/**
* GET /users
* Should render users/index.ejs
*/
it('should render "index" template on GET /users', function(done) {
request(app)
.get('/users')
.end(function(err, res) {
res.statusCode.should.equal(200);
app.didRender(/users\/index\.ejs$/i).should.be.true;
done();
});
});
/*
* GET /users/:id
* Should render users/index.ejs
*/
it('should access User#find and render "show" template on GET /users/:id',
function(done) {
var User = app.models.User;
// Mock User#find
User.find = sinon.spy(function(id, callback) {
callback(null, new User);
});
request(app)
.get('/users/42')
.end(function(err, res) {
res.statusCode.should.equal(200);
User.find.calledWith('42').should.be.true;
app.didRender(/users\/show\.ejs$/i).should.be.true;
done();
});
});
});
这些都失败了,AssertionError: expected 403 to equal 200
要么AssertionError: expected false to be true