玩笑:如何使用动态环境变量?

问题描述 投票:1回答:1

Context

由于某种原因,我通过将脚本标签插入index.html中来动态地使用环境变量(开发,生产...)。在该脚本中,我定义了包含环境变量的全局变量。

env.js

window.globalConfig = {
  REACT_APP_SERVER_URL: "http://api.somesite.co.kr"
}

[App.tsx在运行时使用此变量,但是App.test.tsx失败,导致如下所示的错误。

TypeError:无法读取未定义的属性'REACT_APP_SERVER_URL'

index.html

<script src="./env.js"></script>
<script src="./bundle.js></script>

App.test.tsx

it('render App', () => {
  render(<App />);
});

App.tsx

...window.globalConfig('REACT_APP_SERVER_URL')...

使用脚本标记时如何在Jest中使用动态变量?

reactjs environment-variables jest
1个回答
0
投票

在CRA(Create-React-App)中,react-scripts使用setupTests.ts文件,因此,如果导入包含全局变量的文件,则可以解决。

setupTests.ts

import './env.js'
© www.soinside.com 2019 - 2024. All rights reserved.