使用 Jest 或 Nock 测试异步代码总是返回网络错误。
这是其他人报道的:
https://www.bountysource.com/issues/38003315-network-error-when-using-nock-with-axios
https://stackoverflow.com/questions/42677387/jest-returns-network-error-when-doing-an-authenticated-request-with-axios
我实际上使用了 StackOverflow 上建议的第一个解决方案:“解决方案将 axios 适配器更改为 http”。 这确实有效。
在不强制 http 适配器的情况下,使用 Jest 运行“npm test”会导致测试永远不会完成并永远卡住。
我不确定这是 Axios 问题,而不是 Jest 或 Nock,这不是重点。
奇怪的是下面的堆栈跟踪:在我看来,它正在运行 xhr 实现。 这在node环境下是不是很奇怪?
有没有比 StackOverflow 上建议的更简单的强制使用 http 适配器的方法?
在 createError (node_modules/axios/lib/core/createError.js:16:15) 在 XMLHttpRequest.handleError [as onerror] (node_modules/axios/lib/adapters/xhr.js:87:14) 在 XMLHttpRequest.callback.(匿名函数) (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:289:32) 在 invokeEventListeners (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:219:27) 在 invokeInlineListeners (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:166:7) 在 EventTargetImpl._dispatch (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:122:7) 在 EventTargetImpl.dispatchEvent (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:87:17) 在 XMLHttpRequest.dispatchEvent (node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js:61:35) 在 dispatchError (node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:994:9) 在 validCORSHeaders (node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:1009:7) 在接收响应(node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:871:12) 在 EventEmitter.client.on.res (node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:691:38) 在emitOne (events.js:96:13) 在 EventEmitter.emit (events.js:191:7) 在 Request.realClient.on.res (node_modules/jsdom/lib/jsdom/living/xhr-utils.js:281:49) 在emitOne (events.js:96:13) 在 Request.emit (events.js:191:7) 在 Request.onRequestResponse (node_modules/request/request.js:1074:10) 在emitOne (events.js:101:20) 在 ClientRequest.emit (events.js:191:7) 在 HTTPParser.parserOnIncomingClient (_http_client.js:522:21) 在 HTTPParser.parserOnHeadersComplete (_http_common.js:99:23) 在 Socket.socketOnData (_http_client.js:411:20) 在emitOne (events.js:96:13) 在 Socket.emit (events.js:191:7) 在 readableAddChunk (_stream_readable.js:178:18) 在 Socket.Readable.push (_stream_readable.js:136:10) 在 TCP.onread (net.js:561:20)
如果您查看堆栈跟踪,您会注意到有 jsdom 的痕迹。 这意味着您使用的是 jsdom/浏览器环境而不是节点。 这只是一个开玩笑的配置问题。
我将 package.json 中的测试脚本更改为 "test": "react-scripts test --env=node" 但它仍然对我不起作用。 还有其他地方需要更改吗? (我的项目使用了 create-react-app)
jest --env=node
对我有用。
最有用的评论
如果您查看堆栈跟踪,您会注意到有 jsdom 的痕迹。 这意味着您使用的是 jsdom/浏览器环境而不是节点。 这只是一个开玩笑的配置问题。