CORS 错误 - 错误:禁止跨源 http://localhost - 仅在 ReactJS/Jest 测试中

Dan*_*iel 7 cors reactjs jestjs enzyme

我遇到了一个问题,我向外部 API 发出的请求在执行过程中工作正常,但是在运行 Jest/Enzyme 测试时,它给了我一个 CORS 错误。有问题的函数是使用来自 API 的 JsonRpc 实现,并使用来自 node-fetch 的 fetch。不确定是否有我可以在某处应用的 CORS 设置?

我在 Jest/Enzyme 测试框架中尝试了许多异步等待的变体,但仍然遇到问题。

test("it should do something", done => {
    const component = shallow(<CustomComponent />)
    component.instance().customAsyncFunction( result => {
      expect(result.length).toEqual(5)
      done()
    })
    // return component.instance().customAsyncFunction().then(data => {
    //   expect(data.length).toEqual(5)
    // })
  })
Run Code Online (Sandbox Code Playgroud)

我尝试了上述方法和其他一些方法(例如 setTimeout 并等待它)并得到 CORS 错误。

我得到的结果是:

 console.error
 node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/virtual-console.js:29
   Error: Cross origin http://localhost forbidden
       at dispatchError (...\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\living\xhr-utils.js:65:19)
       at Request.client.on.res (...\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\living\xmlhttprequest.js:679:38)
       at Request.emit (events.js:198:13)
       at Request.onRequestResponse (...\node_modules\request\request.js:1066:10)
       at ClientRequest.emit (events.js:203:15)
       at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:556:21)
       at HTTPParser.parserOnHeadersComplete (_http_common.js:109:17)
       at TLSSocket.socketOnData (_http_client.js:442:20) undefined
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

小智 6

Jest 允许您设置安装脚本文件。在其他所有内容之前都需要此文件,并让您有机会修改测试运行的环境。这样,您可以在加载 axios 之前取消设置 XMLHttpRequest,并在导入提升后评估适配器类型。链接:https ://facebook.github.io/jest/docs/configuration.html#setuptestframeworkscriptfile-string

在 package.json 中

{
  ...,
  "jest": {
    ...,
    "setupTestFrameworkScriptFile": "./__tests__/setup.js",
    ...
  },
  ...
}
__tests__/setup.js

global.XMLHttpRequest = undefined;
Run Code Online (Sandbox Code Playgroud)

  • 我仍然需要 global.XMLHttpRequest 才能工作,因此我使用了“npm install xhr2”,然后是“global.XMLHttpRequest = require('xhr2');”。 (2认同)

Val*_*Shi 6

发生该错误的原因是您在测试期间调用的外部 API 的 CORS 限制与 Jest 的默认限制不同jsdom( http://localhost)。

要修复 Jest v24 - v27 的此问题,您必须在 Jest 配置(例如)中设置适当的testURL(请参阅文档jest.config.js):

{
    // Other config values here ...
    "testURL": "http://localhost:8080"
}
Run Code Online (Sandbox Code Playgroud)

您必须testURL将 CORS 允许的实际 URL 放入远程 API 端。

从 v28 开始,该选项通过testEnvironmentOptions进行了不同的组织,这需要在 Jest 配置中进行不同的更新。


小智 1

1)您可能正在寻找的是使用 jest.mock() 模拟承诺或正在运行的任何函数,然后断言该模拟被调用(使用正确的参数) Jest 测试是不应该的单元测试真正与您的 API 对话

2)在测试模式下,您的环境变量很可能会在开玩笑期间将 process.env.NODE_ENV 设置为“测试”,这可能会更改某些内容或您自己的自定义配置环境变量之一