摩卡在每个testing之前和之后

我一直在尝试使用摩卡testing我的testing服务器。 这是我使用的以下代码,几乎与另一个类似的post中find的代码相同。

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。 你能解释一下我做错了什么吗?

Georgi是正确的,你需要一个调用来指定一个testing,但是如果你不想要的话,你不需要在你的文件中有最高级别的describe 。 你可以用一堆调用来replace你的单个describe

 it("first", function () { // Whatever test. }); it("second", function () { // Whatever other test. }); 

如果你的testing套件很小,并且只有一个文件组成,这个效果会非常好。

如果你的testing套件比较大或者分布在多个文件中,我强烈build议你把beforeEachafterEach与你的it一起放在describe ,除非你绝对肯定套件中的每一个testing都需要beforeEach或者beforeEach afterEach 。 (我已经用Mocha编写了多个testing套件,而且我从来没有beforeEachafterEach ,我需要为每个单独的testing运行。)类似于:

 describe('WebSocket test', function() { beforeEach(function(done) { // ... }); afterEach(function(done) { // ... }); it('response should be null', function() { assert.equal(response.result, null, 'Successful Authentification'); }); }); 

如果你不把你的beforeEachafterEach里面describe ,那么假设你有一个文件来testingweb套接字和另一个文件来testing一些数据库操作。 包含数据库操作testing的文件中的testing将在beforeEachafterEach之前和之后执行。 将beforeEachafterEach放在上面所示的describe中将确保它们仅在您的Web套接字testing中执行。

你的例子中没有testing。 如果没有要运行的testing,那么钩子之前和之后都不会被调用。 尝试添加一个testing,如:

 describe('WebSocket test', function() { it('should run test and invoke hooks', function(done) { assert.equal(1,1); done(); }); });