简体   繁体   English

每次 Karma 测试后如何清理?

[英]How to clean up after each Karma test?

This is my test (Karma + Mocha):这是我的测试(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
  });
});

The afterEach part is exactly the same in all tests. afterEach部分在所有测试中完全相同。 It cleans up the mess after the test.它会在测试后清理混乱。 It's obvious code duplication.这是明显的代码重复。 How can I get rid of it?我怎样才能摆脱它?

You can run a global hook ( before , beforeEach , after and afterEach ) when running each test by defining a method in a setup file.通过在设置文件中定义方法,您可以在运行每个测试时运行全局挂钩( beforebeforeEachafterafterEach )。

test/setup.js测试/setup.js

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

We need to tell Mocha where we can find this file, we can do this by placing the following in the mocha.opts ( https://mochajs.org/#mochaopts ) file.我们需要告诉 Mocha 在哪里可以找到这个文件,我们可以通过将以下内容放在mocha.opts ( https://mochajs.org/#mochaopts ) 文件中来做到这一点。

--file ./test/setup.js

You can read more about it here: https://mochajs.org/#root-level-hooks .你可以在这里阅读更多关于它的信息: https://mochajs.org/#root-level-hooks

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM