问题描述
我使用Jest在节点中进行单元测试.
并且我使用了Jest中的新功能 globalSetup v22.
我已经在 globalSetup 中定义了全局变量.
但是我无法在测试代码中得到它.控制台日志未定义.
有任何疑问吗?
谢谢.
I use Jest to do unit test in node.
And I use the new feature globalSetup which come in Jest v22.
I have defined a global variable in globalSetup.
But I can't get it in the test code. Console log is undefined.
Anyone in this question?
Thanks.
最佳版本:22.0.0
节点版本:8.9.0
纱线版本:1.3.2
操作系统:mac High Sierra 10.13.2
Jest version: 22.0.0
node version: 8.9.0
yarn version: 1.3.2
OS: mac High Sierra 10.13.2
代码如下:
// package.json
{
"jest": {
"globalSetup": "<rootDir>/src/globalSetupTest.js"
}
}
// globalSetupTest.js
module.exports = async function() {
global.foo = 'foo';
console.log(`global setup: ${global.foo}`);
};
// App.test.js
describe('APP test', () => {
it('renders without crashing', () => {
console.log({ foo: global.foo });
});
});
// test result
yarn run v1.3.2
$ node scripts/test.js --env=node --colors
global setup: foo
PASS src/App.test.js
APP test
✓ renders without crashing (5ms)
console.log src/App.test.js:3
{ foo: undefined }
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 0.354s, estimated 1s
Ran all test suites.
推荐答案
Jest人自己提供了一个解决方案: https://jestjs.io/docs/en/puppeteer.html .请注意,如果您使用的是CRA,则无法立即使用(下面的解决方案),因为它目前不支持Jest的testEnvironment选项.
There's a solution offered from Jest people themselves: https://jestjs.io/docs/en/puppeteer.html. Note that if you're using CRA, this won't work out of the box (solution below), cause it currently doesn't support testEnvironment option for Jest.
无论如何:
- 在Jest配置文件中,您设置了指向全局设置,拆卸和测试环境脚本的路径
- 在全局设置脚本中,您创建一个浏览器并将其WSEndpoint写入文件中
- 在全局拆卸脚本中,您只需关闭浏览器
- 在testEnvironment脚本中,您从之前保存的文件中读取WSEndpoint,然后使用它连接到正在运行的浏览器-此后,通过使用全局变量,浏览器可用于您的测试中
如果您使用的是CRA,则可以对这些测试使用自定义设置,然后完全单独运行它们.而且,如果您要使用Puppeteer进行e2e测试,那么无论如何,这可能就是您想要做的.
If you're using CRA, you can use a custom setup for these tests and run them completely separately. And if you're using Puppeteer for e2e tests, this is probably what you want to do anyway.
您只需将另一个脚本添加到package.json:"test:e2e": "jest -c ./jest-e2e.config.js"
并根据需要进行设置.现在,您将具有npm run test
用于单元测试,而npm run test:e2e
用于端到端测试.
You just add another script to your package.json: "test:e2e": "jest -c ./jest-e2e.config.js"
and set it up as you want. Now you will have npm run test
for unit tests and npm run test:e2e
for end to end tests.
这篇关于为什么无法在测试代码中获取在globalSetup中设置的全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!