JEST Express Error: Cross origin http://localhost forbidden

Viewed 3355

I am facing an error using JEST with Express while I execute my test with npm run test.

  console.error
    Error: Cross origin http://localhost forbidden

I've seen similar post like CORS error - Error: Cross origin http://localhost forbidden... without working answers

Here is my test :

const app = require('../app');
const request = require("supertest");
const enjoyService = require('../services/enjoy.service');

describe('/enjoy', () => {
    describe("/cinema/:city", () => {
        test('Status is OK', () => {
            return enjoyService.listCinema("nantes").then(res => {
                expect(res.data.status).toBe('OK');
            });
        });
        test('Status is 404', () => {
            return enjoyService.listCinema("X Æ A-XII").catch(err => {
                expect(err.name).toBe("Error");
            });
        });
    });
});

And the enjoy.service used bellow

const axios = require('axios'),
    googleBaseURL = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=";

function listCinema(city) {
    return axios.get(googleBaseURL + city + '&type=cinema&key=' + process.env.GOOGLE_API)
}

3 Answers

I've found a similar GitHub issue. It could help someone else having the same issue using JEST and ExpressJS

The similar issue says we have to add to our jest.config.js

{
  // ...
  testEnvironment: 'node'
  // ...
}

In my case I added the code bellow to my package.json like so

  "jest": {
    "testEnvironment": "node"
  },

Good to know if you want to add the config from your package.json like me

If you'd like to use your package.json to store Jest's config, the "jest" key should be used on the top level so Jest will know how to find your settings:

{
 "name": "my-project",
 "jest": {
   "verbose": true
 }
}

I have been able to fix this problem by adding this validation snippet:

import axios from 'axios'

if(typeof process != 'undefined'){
  axios.defaults.adapter = require('axios/lib/adapters/http');
}

/.../

More local solution

Instead of changing the test environment globally to make one test work, you could change the test environment or even single environment options for that particular test only by adding a docblock at the top of the test file.

See the docs for further information: https://jestjs.io/docs/configuration#testenvironmentoptions-object

/**
 * @jest-environment-options {"url": "http://other-than-localhost"}
 */

Related