I'm trying to test my service with JEST and mocking endpoint with nock. Service looks like this
export async function get(id) {
const params = {
mode: 'cors',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
};
let response = await fetch(`{$API}/projects/${id}`, params);
return response.json();
}
Test:
import {
get
} from './project';
import nock from 'nock';
const fetchNockProject = nock($API)
.get('/projects/1')
.reply('200', {});
const data = await get(1);
expect(data).resolves.toEqual(project);
When I run the test I get error:
console.error node_modules/jsdom/lib/jsdom/virtual-console.js:29 Error: Cross origin null forbidden
TypeError: Network request failed
Any idea why virtual-console is throwing this as this is only service.
I found a solution for my problem which was connected with CORS. Nock mock should be:
fetchNockProject = nock($API)
.defaultReplyHeaders({
'access-control-allow-origin': '*',
'access-control-allow-credentials': 'true'
})
.get('/projects/1')
.reply('200', project);
Well, the posted answer didn't work for me and while I'm not saying it's wrong I thought I should share what did work for me.
In my case, my server is ASP.NET Core. I wasn't using the Cors middleware module that is provided. I added that in and configured it and that fixed my issue with no change to my javascript files.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With