获取beforeEach,仅在其所在的文件中运行测试

时间:2018-11-08 15:35:29

标签: javascript unit-testing mocha

我有两个Mocha测试文件,每个文件都有自己的beforeEach函数。每个文件中的beforeEach将在所有测试用例中运行。用代码更好地解释:

user.test.js:

beforeEach((done) => {
  console.log('user before each');
  done();
});
describe('Running user tests', () => {

  it('user test #1',  () => {
    console.log('in user test 1');
  });

  it('user test #2',  () => {
    console.log('in user test 2');
  });

});

todo.test.js

beforeEach((done) => {
  console.log('todo before each');
  done();
});

describe('Running todo tests', () => {

  it('todo test #1',  (done) => {
    console.log('in todo test 1');
    done();
  });

  it('todo test #2',  (done) => {
    console.log('in todo test 2');
    done();
  });

});

package.json

{
  "name": "before-each",
  "version": "1.0.0",
  "description": "",
  "main": "todo.test.js",
  "scripts": {
    "test": "mocha **/*.test.js"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "mocha": "^5.2.0"
  }
}

运行时输出:npm test

  Running todo tests
todo before each
user before each
in todo test 1
    ✓ todo test #1
todo before each
user before each
in todo test 2
    ✓ todo test #2

  Running user tests
todo before each
user before each
in user test 1
    ✓ user test #1
todo before each
user before each
in user test 2
    ✓ user test #2


  4 passing (7ms)

有什么方法可以使todo文件中的beforeEach()仅针对todo文件中的测试运行,而使用户文件中的beforeEach()仅针对用户测试运行?我来自Java / JUnit背景,其行为却大不相同。

谢谢!

1 个答案:

答案 0 :(得分:2)

beforeEach移到describe内。这是放置属于特定beforeEach的{​​{1}}的正确位置:

describe