CRA - window 对象未定义 - jest/react

CRA - window object is undefined - jest/react

我在测试中遇到一个问题,将 window 变量标记为未定义。但是我不知道在 setupTests.tsx 的什么地方,我需要定义它。到目前为止,变量是这样使用的:

index.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>

config.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 设置的想法吗?

由于您没有在测试环境中定义环境变量,您可以简单地回退到硬编码 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 中的所有附加代码。