12

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.

skyboyer
  • 22,209
  • 7
  • 57
  • 64
MarJano
  • 1,257
  • 2
  • 18
  • 39

2 Answers2

31

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);
Maksim Nesterenko
  • 5,661
  • 11
  • 57
  • 91
MarJano
  • 1,257
  • 2
  • 18
  • 39
1

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.

Frank V
  • 25,141
  • 34
  • 106
  • 144
  • The OP was mocking fetch(), and so it's also necessary to mock the "access-control-allow-origin" header. Since you're connecting to a real server, you want the server to send a real such header (which is what the CORS middleware does) – Andy Mar 26 '20 at 14:35