我的应用程序在运行时使用窗口对象为docker注入环境变量,但我的测试返回错误如下:
url配置:
declare const window: Window &
typeof globalThis & {
_env_: any
}
export const url = window._env_.REACT_APP_API_URL;
export const baseUrl = url;
测试中的错误,因为处理程序使用baseUrl,但即使我将处理程序更改为硬编码值,也会出现以下错误:
●测试套件无法运行类型错误:无法读取未定义(读取"REACT_APP_API_URL")的属性
4 | }
5 |
> 6 | export const url = window._env_.REACT_APP_API_URL;
| ^
7 | export const baseUrl = url;
setupTests.tsx
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';
import { setLogger } from 'react-query'
import { server } from './mocks/server'
declare const window: Window &
typeof globalThis & {
_env_: any
}
window._env_.REACT_APP_API_URL = "https://wwww.xxxxx.com"
beforeAll(() => server.listen())
// Reset any request handlers that we may add during the tests,
// so they don't affect other tests.
afterEach(() => server.resetHandlers())
// Clean up after the tests are finished.
afterAll(() => server.close())
// silence react-query errors
setLogger({
log: console.log,
warn: console.warn,
error: () => {},
})
有什么想法吗?因此,在任何有api调用的地方,我都会在jest/Rect的测试中得到这个错误。
您可以模拟全局window
var
test/setup.js
window.env. REACT_APP_API_URL = 'something';
然后你需要添加package.json
文件
"jest": {
"setupFiles": [
"./test/setup.js"
],
或
您可以在CLI中定义全局var,如以下
npm run jest -- --globals='{"window": "someUrl", "value": "someValue"}'