我试图在sailsjs中编写一些集成测试。我有一个bootstrap.test.js文件,它在docs suggest之前将我的服务器提升到全局。
在我的集成测试中,当我尝试将我的sails应用程序传递给supertest时,我收到错误:
app is not defined
agent = request.agent(app.hooks.http.app);
^
bootstrap.test.js
var Sails = require('sails'),
Barrels = require('barrels'),
app;
before(function(done) {
console.log('Global before hook'); // Never called?
this.timeout(5000);
Sails.lift({
log: {
level: 'error'
},
models: {
connection: 'test',
migrate: 'drop'
}
}, function(err, sails) {
app = sails;
if (err) return done(err);
var barrels = new Barrels();
fixtures = barrels.data;
barrels.populate(function(err) {
done(err, sails);
});
});
});
// Global after hook
after(function (done) {
console.log(); // Skip a line before displaying Sails lowering logs
Sails.lower(done);
});
集成测试
var chai = require('chai'),
expect = chai.expect,
request = require('supertest'),
agent = request.agent(app.hooks.http.app);
describe('Species CRUD test', function() {
it('should not allow an unauthenticated user create a species', function(done){
var species = {
scientificName: 'Latin name',
commonName: 'Common name',
taxon: 'Amphibian',
leadOffice: 'Vero Beach',
range: ['Florida', 'Georgia']
};
agent.post('species')
.send(species)
.end(function(err, species) {
expect(err).to.exist;
expect(species).to.not.exist;
done();
});
});
});
答案 0 :(得分:4)
我一直在努力让集成测试工作几天。这似乎在我的环境中正常工作。也许你可以尝试一下。
<强> bootstrap.test.js 强>
var Sails = require('sails');
var sails;
before(function(done)
{
Sails.lift({
log: {
level: 'error'
},
connections: {
testDB: {
adapter: 'sails-memory'
}
},
connection: 'testDB',
}, function(err, server)
{
sails = server;
if (err) return done(err);
done(err, sails);
});
});
after(function(done)
{
Sails.lower(done);
});
<强>测试强>
var request = require('supertest');
it('should return all users', function(done){
request(sails.hooks.http.app)
.get('/user)
.expect(200)
.expect('Content-Type', /json/)
.end(function(err, res){
// check the response
done();
);
}
我将bootstrap.test.js放在我的测试文件夹的根目录上,然后使用mocha来运行测试。
mocha test/bootstrap.test.js test/**/*.test.js
希望得到这个帮助。
答案 1 :(得分:0)
看来,自Mocha 3.x版以来,nodejs全局变量功能已被删除。因此,如果您需要它,则应将其专门传递给您的环境,例如:
mocha --globals global test/bootstrap.test.js test/**/*.test.js
或 在您的mocha.opts文件中:
#test/mocha.opts
--globals global