Why do I have to set CORS to true in this simple scenario? (JEST)


#1

Hi. I have the following merely illustrative piece of code. I’m using jest and a cucumber dialect here, but that’s not important I think. A segment of the code uses “request”, the other part uses “axios”. Both do the same, both do make a HTTP request to a server instance running on localhost. However, in order to work, axios requires me to set CORS to true, while request does not need that.
Any idea on why does this happen?

import { loadFeature, defineFeature } from 'jest-cucumber'
import request from 'request'
import axios from 'axios'

const feature = loadFeature('./specs/features/hot-content.feature')

defineFeature(feature, test => {
  test('Scenario headline', ({ given, when, then }) => {
    given('Feature headline', () => {})

    when('condition', () => {
      request('http://127.0.0.1:3333/', (error, response, body) => {
        expect(response.statusCode).toBe(200)
      })
    })

    then('consequence', async () => {
      let response = await axios.get('http://localhost:3333')
      expect(response.status).toBe(200)
    })
  })
})

#2

Does your tests runs in the context of browser? If yes, then you have to enable CORS.


#3

No, I’m not running axios in the browser, it’s running in node, inside a running Adonis project. Do I need to set up a custom header or something? i.e something like the following:

var config = {
  headers: {'A-Custom-Header': 'Header-Value'}
};
axios.get('http://127.0.0.1:3333/', config);

#4

I found the problem. Most answers on the web only tell developers to config their server to allow CORS, but they are wrong.

It’s a issue due to Jest default environment.

The default environment in Jest is a browser-like environment through jsdom. If you are building a node service, you can use the node option to use a node-like environment instead.

The solution is simple: set testEnvironment to node in your config

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

Thank you for pointing me in the right direction.