5

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.

Tim Perry
  • 11,766
  • 1
  • 57
  • 85
Marvin
  • 2,537
  • 24
  • 35
  • 2
    wow, what a surprise! check the thread https://github.com/axios/axios/issues/2654 and please-please compose an "official answer" if any advise here works to you. – skyboyer Aug 08 '20 at 23:47
  • Interestingly, I had read that and thought -- too much going on here. And switched to `got` instead of `axios`, problem solved. But I revisited, and it is "simple". – Marvin Aug 09 '20 at 13:59
  • yeah, axios delegates to jest that delegates to jsdom and latter mimics browser's behavior and sends OPTIONS. Two many things happen. – skyboyer Aug 09 '20 at 17:33

1 Answers1

5

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);
  });
});
Marvin
  • 2,537
  • 24
  • 35