【问题标题】:How to clean up after each Karma test?每次 Karma 测试后如何清理?
【发布时间】:2020-05-01 18:11:20
【问题描述】:

这是我的测试(Karma + Mocha):

describe('foo', function() {
  afterEach(function() {
    var id = window.setTimeout(function() {}, 0);
    while (id--) {
      window.clearTimeout(id);
    }
  });
  it('works', function() {
    document.body.innerHTML = '<html/>';
    // add some timeouts here
  });
});

afterEach 部分在所有测试中完全相同。它会在测试后清理混乱。这是明显的代码重复。我怎样才能摆脱它?

【问题讨论】:

    标签: javascript mocha.js karma-runner


    【解决方案1】:

    您可以在运行每个测试时通过在设置文件中定义一个方法来运行全局挂钩(beforebeforeEachafterafterEach)。

    test/setup.js

    beforeEach(async () => {  
      // your code
    })
    

    我们需要告诉 Mocha 在哪里可以找到这个文件,我们可以通过将以下内容放入 mocha.opts (https://mochajs.org/#mochaopts) 文件中来做到这一点。

    --file ./test/setup.js
    

    您可以在此处阅读更多信息:https://mochajs.org/#root-level-hooks

    【讨论】:

      猜你喜欢
      • 2020-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多