Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing with JEST and nock causing 'Cross origin null forbidden'

Tags:

jestjs

nock

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.

like image 971
MarJano Avatar asked Mar 20 '18 14:03

MarJano


2 Answers

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);
like image 173
MarJano Avatar answered Nov 05 '22 13:11

MarJano


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.

like image 20
Frank V Avatar answered Nov 05 '22 13:11

Frank V