CORS错误-错误:禁止跨源http://localhost-仅限JS/JEST测试 [英] CORS error - Error: Cross origin http://localhost forbidden - in ReactJS/Jest test only

查看:18
本文介绍了CORS错误-错误:禁止跨源http://localhost-仅限JS/JEST测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我在JEST/酶测试框架中尝试了许多不同的异步等待,但仍然遇到问题。

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)
    // })
  })

我尝试了上述方法和其他几种方法(如setTimeout和Waiting It),但收到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 (...
ode_modulesjest-environment-jsdom
ode_modulesjsdomlibjsdomlivingxhr-utils.js:65:19)
       at Request.client.on.res (...
ode_modulesjest-environment-jsdom
ode_modulesjsdomlibjsdomlivingxmlhttprequest.js:679:38)
       at Request.emit (events.js:198:13)
       at Request.onRequestResponse (...
ode_modules
equest
equest.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

有什么想法吗?

推荐答案

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;

这篇关于CORS错误-错误:禁止跨源http://localhost-仅限JS/JEST测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆