NetworkError at XMLHttpRequest.send
josuevalrob opened this issue · comments
Test:
describe('When function authApi its passed', () => {
test("Authentication services", async () => {
const user: Response<UserInfo> = await request.get('user');
// expect(userMock?.lastName).toEqual('Valencia');
expect(user.payload?.lastName).toEqual('Valencia');
});
})
The feature:
import ky from 'ky';
const api = ky.extend({
prefixUrl: '/api/',
retry: 0,
});
export const request: Request = {
get: async <R>(url: string) => {
const res: Response<R> = await api.get(url).json();
return res;
},
}
The error
NetworkError
at XMLHttpRequest.send (/Users/project/ui/.yarn/cache/xhr2-npm-0.2.1/node_modules/xhr2/lib/xhr2.js:281:19)
at /Users/project/ui/.yarn/cache/whatwg-fetch-npm-3.6.2/node_modules/whatwg-fetch/dist/fetch.umd.js:600:11
at new Promise (<anonymous>)
at fetch (/Users/project/ui/.yarn/cache/whatwg-fetch-npm-3.6.2/node_modules/whatwg-fetch/dist/fetch.umd.js:507:12)
at /Users/project/ui/.yarn/cache/ky-npm-0.30.0/node_modules/ky/distribution/utils/time.js:11:10
at new Promise (<anonymous>)
at timeout (/Users/project/ui/.yarn/cache/ky-npm-0.30.0/node_modules/ky/distribution/utils/time.js:3:69)
at Ky._fetch (/Users/project/ui/.yarn/cache/ky-npm-0.30.0/node_modules/ky/distribution/core/Ky.js:213:23)
at async fn (/Users/project/ui/.yarn/cache/ky-npm-0.30.0/node_modules/ky/distribution/core/Ky.js:84:28)
at async Promise.result.<computed> [as json] (/Users/project/ui/.yarn/cache/ky-npm-0.30.0/node_modules/ky/distribution/core/Ky.js:120:39)
Why am i importing XMLHttpRequest
library:
ReferenceError: XMLHttpRequest is not defined
What could be the issue?
@josuevalrob, are you using jsdom
as Jest environment?
Since newer versions of Jest, its default environment is node
now. You need to explicitly install and use jest-environment-jsdom
to run browser-like code:
npm i jest-environment-jsdom -D
// your.test.js
/**
* @jest-environment jsdom
*/
Then XMLHttpRequest
will be globally defined by the environment.
The error right now happens not because of third-party libraries but because your testing environment doesn't know what XMLHttpRequest
is.
I can also see some interesting jest.config.js
setup that I've never seen before. I don't think you can use async functions to create Jest config. It must be a plain object.
This should be fixed with the new examples. Please give them a try!