I am trying to write unit test by mocking axios api calls. Here is the axios-mock-adapter configuration
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);
When I trigger action it calls this API
GET: " https://example.com/searchuser/user/id/560/ "
Here is the complete error log
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
Can someone help me understand how I can mock the preflight calls as well? I need to use jest with jsdom as the other unit tests need to mimic browser behaviour. Searched a lot but can't seem to find a solution.
I made a mistake in mocking axios. I have created instance of axio for making api calls and was trying to mock axios default instance in the above question. So no mock was applied. Following solve the problem.
import AxiosAPIInstance from '/api/instance';
const mock = new MockAdapter(AxiosAPIInstance );
.....
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.