我正在尝试通过模拟 axios api 调用来编写单元测试。这是 axios-mock-adapter 配置
import MockAdapter from 'axios-mock-adapter';
import axios from 'axios';
const mock = new MockAdapter(axios);
it('Get User details without errors', async () => {
const mockData =
'{"userID": 1234, ...}}';
const url = '/user/id/560/';
//const url = 'https://example.com/searchuser/user/id/560/'; Also tried with this
mock.onGet(url).reply(200, mockData);
当我触发操作时,它会调用此 API
获取:“ https://example.com/searchuser/user/id/560/ ”
这是完整的错误日志
console.error node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/virtual-console.js:29
Error: Error: Response for preflight has invalid HTTP status code 403
at Object.dispatchError (C:\Users\lokeshp\branches\nrrui\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\living\xhr-utils.js:65:19)
at EventEmitter.client.on.err (C:\Users\lokeshp\branches\nrrui\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\living\xmlhttprequest.js:676:20)
at EventEmitter.emit (events.js:187:15)
at Request.preflightClient.on.resp (C:\Users\lokeshp\branches\nrrui\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\living\xhr-utils.js:376:16)
at Request.emit (events.js:182:13)
at Request.onRequestResponse (C:\Users\lokeshp\branches\nrrui\node_modules\request\request.js:1066:10)
at ClientRequest.emit (events.js:182:13)
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 与 jsdom 一起使用,因为其他单元测试需要模仿浏览器行为。搜索了很多,但似乎无法找到解决方案。