【问题标题】:Mocha beforeEach and afterEach during testing测试期间的摩卡 beforeEach 和 afterEach
【发布时间】:2014-03-31 13:04:10
【问题描述】:

我一直在尝试使用 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。你能解释一下我做错了什么吗?

【问题讨论】:

    标签: node.js mocha.js


    【解决方案1】:

    Georgi 是正确的,您需要调用 it 来指定测试,但如果您不想在文件中添加顶级 describe,则您的文件是正确的。你可以用一堆it 调用替换你的单个describe

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

    如果您的测试套件很小且仅由一个文件组成,则此方法非常有效。

    如果您的测试套件更大或分布在多个文件中,我会非常强烈建议您将beforeEachafterEachit 放在describe 中,除非您绝对肯定套件中的每个测试都需要 beforeEachafterEach 完成的工作。 (我用 Mocha 编写了多个测试套件,但我从来没有需要为每个测试运行 beforeEachafterEach。)类似:

    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 中,那么假设您有一个文件来测试Web 套接字和另一个文件来测试一些数据库操作。包含数据库操作测试的文件中的测试在它们之前和之后执行您的beforeEachafterEach。将beforeEachafterEach 放在describe 中,如上所示,将确保它们仅针对您的Web 套接字测试执行。

    【讨论】:

      【解决方案2】:

      您的示例中没有测试。如果没有要运行的测试,则不会调用 before 和 after 挂钩。尝试添加如下测试:

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

      【讨论】:

        【解决方案3】:

        您需要在套件回调(例如 describe)中有一个测试回调(例如 it)来执行 beforeEach()afterEach() 挂钩。更多信息https://mochajs.org/#run-cycle-overview

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-05-20
          • 2017-02-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-08-04
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多