我的測驗中有一個問題,將視窗變數標記為未定義。但我不知道在 setupTests.tsx 的哪個位置,我需要定義它。到目前為止,該變數是這樣使用的:
索引.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="%PUBLIC_URL%/config.js"></script>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
配置.js
window._env_ = {
REACT_APP_URL: "https://apiurl.com"
}
如何在應用程式中使用它:
declare const window: Window &
typeof globalThis & {
_env_: any
}
const url = window._env_.REACT_APP_URL;
export const apiUrl = url;
setupTests.tsx我確實嘗試在此處添加它,但它仍然無法正常作業
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_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())
停止測驗的錯誤:
● Test suite failed to run
TypeError: Cannot read properties of undefined (reading 'REACT_APP_URL')
4 | }
5 |
> 6 | const url = window._env_.REACT_APP_URL;
| ^
7 | export const apiUrl = url;
8 |
9 |
有什么想法可以與 Create React App 設定一起使用嗎?
uj5u.com熱心網友回復:
由于您沒有在測驗環境中定義環境變數,您可以簡單地回退到硬編碼url,如下所示。
declare const window: Window &
typeof globalThis & {
_env_: any
}
const url = window._env_.REACT_APP_URL || "https://wwww.xxxxx.com";
export const apiUrl = url;
因此,在REACT_APP_URL定義了環境變數的環境中,它將使用該變數,如果未定義,它將獲取硬編碼的值。
而且,現在您可以從setupTests.tsx.
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/477582.html
