是否可以将jest的测试函数分离到另一个文件中,或者它们必须位于执行文件中?
例如:
test_file.js
function tests (input)
{
it(
"should pass",
function ()
{
expect(input).toBeTrue()
}
)
// more test functions
}
module.exports = tests
main.js
const tests = require("./test_file.js")
describe(
"test block 1",
function ()
{
let input
beforeAll( () => input = true )
tests(input)
}
)
现在,input
总是没有定义
发布于 2019-12-30 04:51:47
让我们添加一些日志,看看执行这段代码的顺序。
main.test.js
const tests = require('./test_file.js');
console.log('000');
describe('test block 1', function() {
let input;
console.log('111');
beforeAll(() => {
console.log('222');
input = true;
});
tests(input);
});
test_file.js
console.log('333');
function tests(input) {
console.log('444');
it('should pass', function() {
console.log('555');
expect(input).toBeTruthy();
});
}
module.exports = tests;
测试结果:
FAIL src/stackoverflow/59520741/main.test.js (9.747s)
test block 1
✕ should pass (7ms)
● test block 1 › should pass
expect(received).toBeTruthy()
Received: undefined
4 | it('should pass', function() {
5 | console.log('555');
> 6 | expect(input).toBeTruthy();
| ^
7 | });
8 | }
9 | module.exports = tests;
at Object.<anonymous> (src/stackoverflow/59520741/test_file.js:6:19)
console.log src/stackoverflow/59520741/test_file.js:1
333
console.log src/stackoverflow/59520741/main.test.js:2
000
console.log src/stackoverflow/59520741/main.test.js:5
111
console.log src/stackoverflow/59520741/test_file.js:3
444
console.log src/stackoverflow/59520741/main.test.js:7
222
console.log src/stackoverflow/59520741/test_file.js:5
555
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 11.015s
现在我们知道了。tests
函数将在jest的测试运行程序收集测试用例之前执行。这意味着您的tests
函数刚刚声明了测试用例(‘111’和'444‘短语)。此时,beforeAll
钩子尚未执行。input
变量的值仍然是undefined
,并传递给tests
函数。
在执行tests
函数之后,将声明测试用例。测试运行程序将收集这些测试用例并以正常的方式运行它们。beforeAll
钩子将首先执行(‘222’短语)。
https://stackoverflow.com/questions/59520741
复制相似问题