在mocha chai-http测试中,我在之前的块中启动了节点服务器。
我让它在单个测试文件中完美地工作。但是,当我试图在一个命令NODE_ENV=test mocha test/**/*.js中运行多个测试时,我得到了一个错误。
我尝试让节点服务器在每个测试文件的不同端口上启动。这不起作用,得到了节点服务器启动错误。
我现在在想,如果我可以有一个在其他测试文件之前运行的mocha文件来启动服务器,然后一个在其他测试文件之后运行的文件来终止/停止服务器,那就太好了。
我该怎么做呢。
下面是我的一些代码:
下面是我的一个测试文件供参考:
var chai = require('chai');
var chaiHttp = require('chai-http');
chai.use(chaiHttp);
var expect = chai.expect;
var Sails = require('sails');
describe('REST User API', function() {
var app; // for access to the http app
var sails; // for starting and stopping the sails server
before(function (done) {
Sails.lift({
port: 3001,
log: {
level: 'error'
}
}, function (_err, _sails) {
if(_err){
console.log("Error!", _err);
done();
}
else {
app = _sails.hooks.http.app;
sails = _sails;
done();
}
});
});
describe("user session", function () {
var res; // http response
var authenticatedUser;
before(function (done) {
chai.request(app)
.post('/users/signin')
.set('Accept', 'application/json')
.set('Content-Type', 'application/json')
.send({ email: 'admin@test.com', password: 'secret'})
.end(function (_res) {
res = _res; // Record the response for the tests.
authenticatedUser = JSON.parse(_res.text); // Save the response user for authenticated tests
done();
});
});
it("should connect with a 200 status", function () {
expect(res).to.have.status(200);
});
it("should have a complete user session", function () {
var userSession = authenticatedUser;
expect(userSession).to.have.property('firstName');
expect(userSession).to.have.property('lastName');
expect(userSession).to.have.property('gender');
expect(userSession).to.have.property('locale');
expect(userSession).to.have.property('timezone');
expect(userSession).to.have.property('picture');
expect(userSession).to.have.property('phone');
expect(userSession).to.have.property('email');
expect(userSession).to.have.property('username');
expect(userSession).to.have.property('confirmed');
expect(userSession).to.have.property('status');
expect(userSession).to.have.property('authToken');
});
});
after(function (done) {
sails.lower(function() {
done()
});
});
});发布于 2020-12-28 14:47:54
在mocha v8.2.0中,您可以使用GLOBAL FIXTURES为所有测试套件设置和关闭您的web服务器。全局fixture保证执行一次且只执行一次。
https://stackoverflow.com/questions/29084968
复制相似问题