fetch 无法正常工作,并返回 TypeError: Network request failed [英] fetch doesn't work in jest, and return TypeError: Network request failed

查看:115
本文介绍了fetch 无法正常工作,并返回 TypeError: Network request failed的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 karma + PhantomJS 迁移到 Jest + jsDom,但我遇到了问题.UT 中的所有获取都在 Jest 中失败.我试图找出原因.所以我就这样写一个简单的UT

I am trying to migrate from karma + PhantomJS to Jest + jsDom, but I got a problem. all fetch in UT failed in Jest. I am trying to figure out the reason. So I just write a simple UT like this

import fetch from 'isomorphic-fetch';
import $ from 'jquery';

describe('test', () => {
  it('should fetch success....', (done) => {
    return fetch('http://www.ebay.com/', { method: 'get' })
    .then((res) => {
      console.log(res);
      done();
    })
    .catch(err => console.log(err));
  })

   it('should get success....', (done) => {
    $.get('http://www.ebay.com/', (res) => {
      console.log(res);
      done();
    }).fail((xhr, statusText, err) => {
      console.log(statusText, err); 
    })
  })
})

但还是会出现这样的错误

but still get the error like this

    TypeError: Network request failed
            at XMLHttpRequest.xhr.onerror (/Users/davidhe/work/activenet/git/aui/node_modules/whatwg-fetch/fetch.js:436:16)
            at XMLHttpRequest.callback.(anonymous function) (/Users/davidhe/work/activenet/git/aui/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/events/EventTa
    rget-impl.js:289:32)
            at invokeEventListeners (/Users/davidhe/work/activenet/git/aui/node_modules/jest-environment-jsdom/node_modules/jsdo

m/lib/jsdom/living/events/EventTarget-impl.js:219:27)
        at invokeInlineListeners (/Users/davidhe/work/activenet/git/aui/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:166:7)
        at EventTargetImpl._dispatch (/Users/davidhe/work/activenet/git/aui/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:122:7)
        at EventTargetImpl.dispatchEvent (/Users/davidhe/work/activenet/git/aui/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:87
:17)
        at XMLHttpRequest.dispatchEvent (/Users/davidhe/work/activenet/git/aui/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js:61:35
)
        at dispatchError (/Users/davidhe/work/activenet/git/aui/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:994:9)
        at validCORSHeaders (/Users/davidhe/work/activenet/git/aui/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:1009:7)
        at receiveResponse (/Users/davidhe/work/activenet/git/aui/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:871:12)
        at Request.client.on.res (/Users/davidhe/work/activenet/git/aui/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:691:38)
        at emitOne (events.js:96:13)
        at Request.emit (events.js:188:7)
        at Request.onRequestResponse (/Users/davidhe/work/activenet/git/aui/node_modules/request/request.js:1074:10)
        at emitOne (events.js:96:13)
        at ClientRequest.emit (events.js:188:7)
        at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:473:21)
        at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)
        at Socket.socketOnData (_http_client.js:362:20)
        at emitOne (events.js:96:13)
        at Socket.emit (events.js:188:7)
        at readableAddChunk (_stream_readable.js:176:18)
        at Socket.Readable.push (_stream_readable.js:134:10)
        at TCP.onread (net.js:547:20)

这是我的 package.json

this is my package.json

 {
   devDependencies:{   
      "jsdom": "^11.0.0",
      "babel-jest": "^20.0.3",
      "jest": "^20.0.4"
    },
"dependencies": {
   "isomorphic-fetch": "^2.2.1"
}
"jest": {
    "browser": true,
    "testEnvironment": "jsdom",
    "cacheDirectory": "./node_modules/.cache",
    "verbose": true,
    "globals": {
      "__STATIC__": true,
      "__DEV__": false,
      "__TESTING__": true
    },
    "transformIgnorePatterns": [
      "/node_modules/(?!react-aaui).+\.js$"
    ],
    "moduleNameMapper": {
      "\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/test/__mocks__/fileMock.js",
      "\.(css|less)$": "<rootDir>/test/__mocks__/styleMock.js",
      "^imports": "<rootDir>/test/__mocks__/jestImportsMock.js"
    },
    "testRegex": "(fetch\.(test|spec))\.(jsx|js)$",
    "moduleFileExtensions": [
      "json",
      "jsx",
      "js"
    ],
    "moduleDirectories": [
      "node_modules",
      "src",
      "test"
    ],
    "modulePathIgnorePatterns": [],
    "snapshotSerializers": [
      "enzyme-to-json/serializer"
    ],
    "collectCoverage": false,
    "collectCoverageFrom": [
      "src/**/*.{js,jsx}",
      "!**/__mocks__/**"
    ],
    "coverageReporters": [
      "text",
      "html"
    ],
    "coverageDirectory": "test/coverage",
    "setupFiles": [
      "./test/tests.initialState.jest.js"
    ],
    "testPathIgnorePatterns": [
      "/node_modules/",
      "/examples/",
      "/dist/"
    ]
  }
    }

任何人都可以帮助我.

推荐答案

这个问题通过add解决了

this question is resolved by add

import { XMLHttpRequest } from 'xmlhttprequest';
global.XMLHttpRequest = XMLHttpRequest;

在 tests.initialState.jest.js 中.

in tests.initialState.jest.js.

之前,我用的是w3c-xmlhttprequest,结果不行.

before, I was using w3c-xmlhttprequest, and it doesn't work.

这篇关于fetch 无法正常工作,并返回 TypeError: Network request failed的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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