node.js - Mocha beforeEach vs 执行前

我最近遇到了一个我无法解释的问题。我在这些测试中有很多代码,所以我将尽我所能在这里捕捉到这个想法

我的测试看起来像:

describe('main page', function() {
  beforeEach(function(done){
    addUserToMongoDb(done);   // #1
  });

  afterEach(function(done) {
    removeUserFromMongoDb(done);
  });

  context('login', function() {
     it('should log the user in', function() {
       logUserIn(user_email);  // #2 - This line requires the user from the beforeEach
     });
  });

  context('preferences', function() {
    before(function(done) {    //#3
       logUserInBeforeTest(user_email);
     });

    it('should show the preferences', function() {
       doCheckPreferences(); // #4
    });
  });
});

问题是, #1 的 beforeEach 运行良好。我可以看到它发生在数据库上,并且 #2 中的测试通过了。

但是,在 #4 的首选项上下文中的测试失败,因为它无法在 #3 找到用户登录。

似乎上下文 before 在描述 beforeEach 之前执行,这导致它们失败。如果我将 logUserIn 移动到 it block 中,它可以正常工作。

这是什么原因造成的?

最佳答案

虽然这个答案只是再次显示文档说明,并且有一些评论试图帮助显示差异,但应该引用@tomasz-wszelaki 下面的答案。

Mocha 的测试运行器在 Hooks section of the Mocha Test Runner 中对这个功能进行了最好的解释。 .

来自 Hooks 部分:

describe('hooks', function() {

    before(function() {
        // runs before all tests in this file regardless where this line is defined.
    });

    after(function() {
        // runs after all tests in this file
    });

    beforeEach(function() {
        // runs before each test in this block
    });

    afterEach(function() {
        // runs after each test in this block
    });

    // test cases
});

您可以将这些例程嵌套在其他描述 block 中,这些 block 也可以具有 before/beforeEach 例程。

https://stackoverflow.com/questions/32660241/

相关文章:

javascript - 通过 JavaScript 直接访问 MongoDB

mongodb - 如何在 Mongodb 的字段中查找子字符串

arrays - 更新 mongodb 中的嵌套数组

mongodb - 如何限制 mongodb 中更新文档的数量

node.js - 处理 Mongoose 验证错误——在哪里以及如何处理?

mongodb - 如何将元素插入 MongoDB 内部列表?

node.js - 如何在 MongoDB collection.find() 上获取回调

mongodb - 启动 mongod fork,ERROR : child process fai

mongodb - 从 Mongo 获取 BinData UUID 作为字符串

mongodb - 使用新的 _id 在 MongoDB 中复制文档