Node.js 测试期间,每次前后都要喝摩卡咖啡

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(

我一直在尝试使用mocha测试我的测试服务器。这是我使用的以下代码,与另一篇类似文章中的代码几乎相同

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。更多信息