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);