【发布时间】:2014-01-22 21:08:47
【问题描述】:
在编写自动化系统/集成测试时,在所有测试之前运行的第一步通常是“启动服务器”。由于启动服务器的成本可能很高,因此最好只做一次,而不是在每次单独测试之前。 JUnit has easy functionality for doing this. nodeunit 中是否有等效的标准模式?还是需要手动滚动?
【问题讨论】:
标签: node.js integration-testing nodeunit
在编写自动化系统/集成测试时,在所有测试之前运行的第一步通常是“启动服务器”。由于启动服务器的成本可能很高,因此最好只做一次,而不是在每次单独测试之前。 JUnit has easy functionality for doing this. nodeunit 中是否有等效的标准模式?还是需要手动滚动?
【问题讨论】:
标签: node.js integration-testing nodeunit
我不认为 Nodeunit 有这个内置的,但是很多人用 Grunt 处理这样的任务。
【讨论】:
因为您使用 nodeunit 的测试套件只是节点模块,您可以利用该闭包进行全局设置/拆卸(仅适用于该测试套件):
var myServer = require('./myservermodule');
var testsRun = 0;
var testsExpected = 3;
function startTest(test) {
test._reallyDone = test.done;
test.done = function() {
++testsRun;
test._reallyDone();
};
}
module.exports = {
'setUp' : function(cb) {
if (!myServer.server) myServer.start(cb);
else cb();
},
'tearDown' : function(cb) {
console.log("Tests run: " + testsRun + "/" + testsExpected);
if (testsRun===testsExpected) myServer.stop(cb);
else cb();
},
'sometest1' : function(test) {
startTest(test);
test.expect(1);
test.ok(true);
test.done();
},
'sometest2' : function(test) {
startTest(test);
test.expect(1);
test.ok(false);
test.done();
},
'sometest3' : function(test) {
startTest(test);
test.expect(1);
test.ok(true);
test.done();
}
};
【讨论】:
是的,Nodeunit 有一个 setUp() 和一个 tearDown() 函数,它们总是在测试之前和之后运行。您可以使用setUp() 像这样启动您的服务器:
var server = require("path/to/server.js");
exports.setUp = function(callback) {
server.start(8080, function() {
callback();
});
};
// run your tests here, setUp will be called before each of them
这假设你在 server.js 中有:
exports.start = function() {
// start server here
}
tearDown() 函数在调用test.done() 之后运行。
有关此示例,请在此处查看实际操作:https://github.com/jamesshore/Lessons-Learned-Integration-Testing-Node/blob/master/src/_server_test.js
文档在这里:https://github.com/caolan/nodeunit#groups-setup-and-teardown
【讨论】:
有两种方法可以做到这一点:
nodeunit 测试文件中的所有测试都是按顺序同步运行的。您可以将这组测试的设置代码放在第一个测试中,然后将拆解放在最后一个测试中。
如果您想更正式地执行此操作,并且不想为单元测试设置 Grunt,还有一个名为“nodeunit-async”的模块可以让您在之前运行全局设置和拆卸在你所有的测试之后。您可以在一组测试之前和之后运行一次全局设置和拆卸。
这是 nodeunit-async 的简介:
用于运行异步节点单元测试的轻量级包装器。当您希望为跨多个文件的每个测试运行通用的全局设置或拆卸函数,和/或在所有测试之前和之后运行一次夹具设置或拆卸函数时,特别有用。
专为使用异步的自动和瀑布方法编写的单元测试而设计。
【讨论】: