【问题标题】:How can you avoid prevent a beforeEach from running before one particular it block?如何避免阻止 beforeEach 在某个特定的 it 阻塞之前运行?
【发布时间】:2016-08-15 07:16:11
【问题描述】:
describe('1', function () {
  beforeEach(function () {
    // do this before each it EXCEPT 1.5
  });
  it('1.1', function () {

  });
  it('1.2', function () {

  });
  it('1.3', function () {

  });
  it('1.4', function () {

  });
  it('1.5', function () {
    // beforeEach shouldn't run before this
  });
});

我想阻止 beforeEachit1.5 之前运行。我该怎么做?

【问题讨论】:

标签: javascript mocha.js


【解决方案1】:

选项 1

我建议使用嵌套您的描述,例如:

describe('1', function () {

  describe('1 to 4', function () {

    beforeEach(function () {
      // do this before each it EXCEPT 1.5
    });
    it('1.1', function () {

    });
    it('1.2', function () {

    });
    it('1.3', function () {

    });
    it('1.4', function () {

    });
  });

  describe('only 5', function () {
     it('1.5', function () {
     // beforeEach shouldn't run before this
  });

});

在幕后描述将注册 beforeEach 函数,如果存在,它将为所有 itFunctions 调用。


选项 2

it 函数将按顺序调用,因此您还可以使用闭包来控制 beforeEach 何时运行 - 但它有点 hacky - 例如:

describe('1', function () {
  var runBefore = true
  beforeEach(function () {
    // do this before each it EXCEPT 1.5
    if (runBefore) {
        // actual code
    }
  });
  // functions removed for brevity    
  it('1.4', function () {
      runBefore = false;
  });
  it('1.5', function () {
    // beforeEach shouldn't run before this

    // turn it back on for 1.6
    runBefore = true;
  });
});

【讨论】:

    【解决方案2】:

    您可以通过avoiding nesting when you're testing 实现这一目标。这个想法是避免不必要的抽象,而是提取一些将设置您的测试用例的函数,然后在需要的地方调用这个函数。

    这导致代码更易读且更易于维护。无需通过跟踪所有嵌套的beforeEach 调用来了解测试用例中发生了什么,您只需逐行阅读即可。它使您的问题解决起来很简单:

    const setupTestCase = () => {
      // put the code here, instead of in beforeEach
      // if you're doing multiple actions, put them in separate functions and call them one by one
      // this makes your test more readable and easier to maintain
    };
    
    describe('1', function () {
      it('1.1', function () {
        setupTestCase();
        // do test stuff
      });
      it('1.2', function () {
        setupTestCase();
        // do test stuff
      });
      it('1.3', function () {
        setupTestCase();
        // do test stuff
      });
      it('1.4', function () {
        setupTestCase();
        // do test stuff
      });
      it('1.5', function () {
        // here we simply don't call setupTestCase()
        // do test stuff
      });
    });
    

    PS。同样在许多情况下,您不需要顶级 describe 块,只需将每个顶级 describe 移动到单独的文件中,就可以使您的代码更具可读性并为自己节省一层嵌套。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-27
      • 1970-01-01
      • 2014-03-29
      • 2017-08-17
      • 1970-01-01
      相关资源
      最近更新 更多