mocha:如何运行依赖于测试结果的清理

时间:2016-03-18 09:05:37

标签: javascript unit-testing mocha chai

如何在mocha中启动一些依赖于测试结果的清理?
e.g。

describe('some nice tests', () => {
  //cleanup functions
  let cleanup1 = () => 'cleanup1';
  let cleanup2 = () => 'cleanup2';
  let cleanup3 = () => 'cleanup3';
  let cleanup4 = () => 'cleanup4';

  afterEach(() => {
    //no universal cleanup possible
  });

  it('test1', () => {
    //if failed use cleanup1()
    //if success use cleanup2()
  });

  it('test2', () => {
    //if failed use cleanup3()
    //if success use cleanup4()
  });

});

一种可能的解决方案是:

describe('some nice tests', () => {
  //cleanup functions
  let cleanupAfterFail = () => 'nothing';
  let cleanupAfterSuccess = () => 'nothing';

  afterEach(function() {
    if (this.currentTest.state === 'failed') {
      cleanupAfterFail();
    } else {
      cleanupAfterSuccess();
    }

  });

  it('test1', () => {
    cleanupAfterFail = () => 'what i need in fail case 1';
    cleanupAfterSuccess = () => 'what i need in success case 1';
  });

  it('test2', () => {
    cleanupAfterFail = () => 'what i need in fail case 2';
    cleanupAfterSuccess = () => 'what i need in success case 2';
  });

});

但它看起来不是一种正确的方式。

有没有正确的方法呢?如果是,它看起来如何?

我使用mocha 2.4.5
柴2.2.0
这些测试是在现实生活中使用量角器e2e + chai-as-promise。但我认为在这种情况下并不重要。

0 个答案:

没有答案