Jest returns “Network Error” when doing an authenticated request with axios

后端 未结 4 593
被撕碎了的回忆
被撕碎了的回忆 2021-02-02 09:14

This seems a bit weird to me. I\'m trying to test an actual (ie. real network) request with Jest.

These are the tested scenarios:

  • Test an external API (fix
4条回答
  •  失恋的感觉
    2021-02-02 09:37

    Jest allows you to set a setup script file. This file will be required before everything else and gives you a chance to modify the environment in which the tests will run. This way you can unset XMLHttpRequest before axios is loaded and the adapter type evaluated since imports are hoisted. https://facebook.github.io/jest/docs/configuration.html#setuptestframeworkscriptfile-string

    This worked for me:

    package.json

    {
      ...,
      "jest": {
        ...,
        "setupTestFrameworkScriptFile": "./__tests__/setup.js",
        ...
      },
      ...
    }
    

    __tests__/setup.js

    global.XMLHttpRequest = undefined;
    

提交回复
热议问题