Node.js 测试期间,每次前后都要喝摩卡咖啡
我一直在尝试使用mocha测试我的测试服务器。这是我使用的以下代码,与另一篇类似文章中的代码几乎相同Node.js 测试期间,每次前后都要喝摩卡咖啡,node.js,mocha.js,Node.js,Mocha.js,我一直在尝试使用mocha测试我的测试服务器。这是我使用的以下代码,与另一篇类似文章中的代码几乎相同 beforeEach(function(done) { // Setup console.log('test before function'); ws.on('open', function() { console.log('worked...'); done(); }); ws.on('close', function(
beforeEach(function(done) {
// Setup
console.log('test before function');
ws.on('open', function() {
console.log('worked...');
done();
});
ws.on('close', function() {
console.log('disconnected...');
});
});
afterEach(function(done) {
// Cleanup
if(readyState) {
console.log('disconnecting...');
ws.close();
} else {
// There will not be a connection unless you have done() in beforeEach, socket.on('connect'...)
console.log('no connection to break...');
}
done();
});
describe('WebSocket test', function() {
//assert.equal(response.result, null, 'Successful Authentification');
});
问题是,当我执行此草稿时,预期看到的console.log在命令提示符上都不可见。你能解释一下我做错了什么吗 您的示例中没有测试。如果没有要运行的测试,则不会调用before和after挂钩。尝试添加一个测试,如:
describe('WebSocket test', function() {
it('should run test and invoke hooks', function(done) {
assert.equal(1,1);
done();
});
});
Georgi是正确的,您需要一个
it
调用来指定测试,但如果不想,您不需要在文件中有一个顶级description
。您可以将单个descripe
替换为一组it
调用:
it("first", function () {
// Whatever test.
});
it("second", function () {
// Whatever other test.
});
如果您的测试套件很小并且只由一个文件组成,那么这将非常有效
如果您的测试套件较大或分布在多个文件中,我强烈建议您将放在每个之前和之后以及它放在描述中,除非您绝对肯定套件中的每个测试都需要在每次测试之前
或之后
完成。(我已经用Mocha编写了多个测试套件,而且我从来没有在每次测试之前
或之后
都需要运行的)类似于:
describe('WebSocket test', function() {
beforeEach(function(done) {
// ...
});
afterEach(function(done) {
// ...
});
it('response should be null', function() {
assert.equal(response.result, null, 'Successful Authentification');
});
});
如果您没有像这样将放在每个之前和之后中描述,那么假设您有一个文件用于测试web套接字,另一个文件用于测试某些数据库操作。包含数据库操作测试的文件中的测试也将在每个测试之前和之后执行beforeach
和afterEach
。如上图所示,将在每个之前和之后放入描述中,将确保它们仅用于您的web套接字测试。您需要在套件回调(例如描述)中有一个测试回调(例如it
)来执行在每个()之前和之后()
hooks。更多信息