Fetch没有用firebase和jest定义

oxf4rvwz  于 2023-09-28  发布在  Jest
关注(0)|答案(1)|浏览(144)

我尝试在我的Next.js项目上运行jest测试。但我不能,因为我总是得到:

src/lib/utils/item.utils.test.tsx
  ● Test suite failed to run

    ReferenceError: fetch is not defined

      32 | export const firebaseConfig = {
      33 |   apiKey: process.env.NEXT_PUBLIC_FIREBASE_PUBLIC_API_KEY,
    > 34 |   authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
         |                    ^
      35 |   databaseURL: process.env.NEXT_PUBLIC_FIREBASE_DATABASE_URL,
      36 |   projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
      37 |   storageBucket: process.env.NEXT_PUBLIC_STORAGE_BUCKET,

      at Object.<anonymous> (node_modules/@firebase/functions/src/index.ts:28:19)
      at Object.<anonymous> (node_modules/firebase/functions/dist/index.cjs.js:5:17)
      at Object.<anonymous> (src/firebase/firebase.config.tsx:34:20)
      at Object.<anonymous> (src/lib/utils/item.utils.ts:27:25)
      at Object.<anonymous> (src/lib/utils/item.utils.test.tsx:6:20)

我尝试安装node-fetch,whatwg-fetch和set global.fetch,但没有任何效果。

jslywgbw

jslywgbw1#

你需要安装(你已经完成了):

"whatwg-fetch": "^3.6.2",
"jest-fetch-mock": "^3.0.3"

然后在你的jest.setup.js中,在文件的顶部添加以下内容:

// Makes fetch available globally to prevent a Warning
import 'whatwg-fetch';
global.fetch = require('jest-fetch-mock');

fetch.mockResponse(JSON.stringify({testing: true})); // mock every fetchCall in all tests with this default value

在测试中,您可以执行以下操作:

import fetch from 'jest-fetch-mock';
fetch.mockResponseOnce(JSON.stringify(null)); // or whatever you want as response, for that specific test.

如果你已经做了所有这些,但仍然遇到问题,我认为你的库设置或组合有问题。因此,要获得帮助,您需要共享jest.setup、jest.config、使用的版本和testFile的相关部分。

相关问题