我们将 app.js 配置为在从测试运行时在不同的端口上启动,以便我们可以让开发服务器同时在其常规端口上运行(使用 nodemon)。这是我们的代码:
// Start server.
if (process.env.TEST == 'true') {
var port = process.env.PORT || 3500; // Used by Heroku and http on localhost
process.env['PORT'] = process.env.PORT || 4500; // Used by https on localhost
}
else {
var port = process.env.PORT || 3000; // Used by Heroku and http on localhost
process.env['PORT'] = process.env.PORT || 4000; // Used by https on localhost
}
http.createServer(app).listen(port, function () {
console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
});
// Run separate https server if not on heroku
if (process.env.HEROKU != 'true') {
https.createServer(options, app).listen(process.env.PORT, function () {
console.log("Express server listening with https on port %d in %s mode", this.address().port, app.settings.env);
});
};
然后,一个 mocha 文件,例如这个测试网站图标服务的文件,如下所示:
process.env['TEST'] = 'true'; // Use test database
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0" // Avoids DEPTH_ZERO_SELF_SIGNED_CERT error for self-signed certs
var request = require("request").defaults({ encoding: null });
var crypto = require('crypto');
var fs = require('fs');
var expect = require('expect.js');
var app = require("../../app.js");
var hash = function(file) { crypto.createHash('sha1').update(file).digest('hex') };
describe("Server", function () {
after(function () {
process.env['TEST'] = 'false'; // Stop using test database.
});
describe("Static tests", function () {
it("should serve out the correct favicon", function (done) {
var favicon = fs.readFileSync(__dirname + '/../../../public/img/favicon.ico')
request.get("https://localhost:" + process.env.PORT + "/favicon.ico", function (err, res, body) {
// console.log(res)
expect(res.statusCode).to.be(200);
expect(hash(body)).to.be(hash(favicon));
done();
});
});
});
});
另请注意,虽然 grunt 是一个很棒的工具,但您可以从 package.json 脚本部分调用 mocha,然后npm test
运行它。