How can you configure axios running in jest to NOT send OPTIONS before POST?

Viewed 695

From node.js this works as expected, a POST response is sent (as I verified with httpToolkit)

% node
> const axios = require('axios')
> var r = (async () => { const x = await axios.post('http://example.com/v1/secret/data/foo/bar/baz',{data: {foo: 42}},{headers: {'X-Special-Token': 'DATA'}}); return true;})().then(console.log)
undefined
> true

But then doing the same from a jest test, axios is sending an OPTIONS request first. The service I am running is not able to handle that (not example.com)

const axios = require('axios');

describe('Simple Post', () => {
  test('POST', async () => {
    // Axios HERE seems to send an OPTIONS request first...
    const x = await axios.post('http://example.com',
      {data: {foo: 42}},
      {headers: {'X-Special-Token': 'DATA'}});
    expect(x.status).toBe(200);
  });
});

Is there some way to convince/configure jest or axios so that axios does not magically decide to send OPTIONS? This has nothing to do with CORS - its server code talking to server code, but obviously something in axios is deciding that it is appropriate.

1 Answers

Reading through this issue the solution to my problem is simply the header below. See jest test-environment. The issue does have much discussion about different concerns, so YMMV.

/**
 * This is required to prevent axios from acting like it is in a browser
 *   environment and doing OPTIONS preflights, etc.
 *
 * @jest-environment node
 */
const axios = require('axios');

describe('Simple Post', () => {
  test('POST', async () => {
    // No preflight OPTIONS request sent when jest-environment is node
    const x = await axios.post('http://example.com',
      {data: {foo: 42}},
      {headers: {'X-Special-Token': 'DATA'}});
    expect(x.status).toBe(200);
  });
});
Related