JEST Express 错误:跨源 http://localhost 禁止

crg*_*g63 6 node.js express jestjs

我在使用 JEST 和 Express 执行测试时遇到错误npm run test

\n
  console.error\n    Error: Cross origin http://localhost forbidden\n
Run Code Online (Sandbox Code Playgroud)\n

我见过类似的帖子,如CORS 错误 - 错误:跨源 http://localhost 禁止...没有有效的答案

\n

这是我的测试:

\n
const app = require(\'../app\');\nconst request = require("supertest");\nconst enjoyService = require(\'../services/enjoy.service\');\n\ndescribe(\'/enjoy\', () => {\n    describe("/cinema/:city", () => {\n        test(\'Status is OK\', () => {\n            return enjoyService.listCinema("nantes").then(res => {\n                expect(res.data.status).toBe(\'OK\');\n            });\n        });\n        test(\'Status is 404\', () => {\n            return enjoyService.listCinema("X \xc3\x86 A-XII").catch(err => {\n                expect(err.name).toBe("Error");\n            });\n        });\n    });\n});\n
Run Code Online (Sandbox Code Playgroud)\n

enjoy.service使用的波纹管

\n
const axios = require(\'axios\'),\n    googleBaseURL = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=";\n\nfunction listCinema(city) {\n    return axios.get(googleBaseURL + city + \'&type=cinema&key=\' + process.env.GOOGLE_API)\n}\n\n
Run Code Online (Sandbox Code Playgroud)\n

crg*_*g63 8

我发现了类似的 GitHub 问题它可以帮助其他人使用JESTExpressJS遇到同样的问题

类似的问题表明我们必须添加到jest.config.js

{
  // ...
  testEnvironment: 'node'
  // ...
}
Run Code Online (Sandbox Code Playgroud)

就我而言,我将下面的代码添加到我的代码中,package.json如下所示

  "jest": {
    "testEnvironment": "node"
  },
Run Code Online (Sandbox Code Playgroud)

很高兴知道package.json您是否想像我一样添加配置

如果您想使用 package.json 来存储 Jest 的配置,则应在顶层使用“jest”键,以便 Jest 知道如何找到您的设置:

{
 "name": "my-project",
 "jest": {
   "verbose": true
 }
}
Run Code Online (Sandbox Code Playgroud)