[英]How get window values in Tests with Enzyme, Jest + Create React App
Due to the build process I'm using to push my app out I'm passing some environment variables in a file after build, which works fine.由于我用来推出我的应用程序的构建过程,我在构建后在文件中传递了一些环境变量,这工作正常。 However it breaks my tests with the following error message:
但是,它使用以下错误消息破坏了我的测试:
TypeError: Cannot read property 'DATA' of undefined
57 | Auth: {
58 | oth,
> 59 |
| ^
60 |
61 | identity: checkEnv(window.env.DATA,
62 | process.env.REACT_APP_DATA),
I've tried many solutions but have yet to be able to mock the window.env data, how would I do so?我已经尝试了很多解决方案,但还没有能够模拟 window.env 数据,我该怎么做?
Create React App allows you to initialize the test environment by including a src/setupTests.js
file that "will be automatically executed before running your tests". Create React App 允许您通过包含“将在运行测试之前自动执行”的
src/setupTests.js
文件来初始化测试环境。
Create React App also sets up the testing environment with jsdom
which provides the global window
object. Create React App 还使用提供全局
window
对象的jsdom
设置测试环境。
You can set window.env
in src/setupTests.js
and it will be available during your tests:您可以在
src/setupTests.js
设置window.env
,它将在您的测试期间可用:
src/setupTests.js src/setupTests.js
window.env = {
DATA: 'hi'
}
src/code.js源代码/代码.js
export const getData = () => window.env.DATA
src/code.test.js源代码/代码.test.js
import { getData } from './code';
test('env', () => {
expect(getData()).toBe('hi'); // SUCCESS
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.