获取beforeEach仅在其所在的文件中运行测试
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了获取beforeEach仅在其所在的文件中运行测试相关的知识,希望对你有一定的参考价值。
我有两个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背景,这表现得完全不同。
谢谢!
答案
将beforeEach
移动到describe
内。这是放置属于特定beforeEach
的describe
的正确位置:
describe('Running user tests', () => {
beforeEach((done) => {
console.log('user before each');
done();
});
it('user test #1', () => {
console.log('in user test 1');
});
it('user test #2', () => {
console.log('in user test 2');
});
});
以上是关于获取beforeEach仅在其所在的文件中运行测试的主要内容,如果未能解决你的问题,请参考以下文章