Jest returns "Network Error" 在使用 axios 执行经过身份验证的请求时

Jest returns "Network Error" when doing an authenticated request with axios

我觉得这有点奇怪。我正在尝试使用 Jest 测试实际(即真实网络)请求。

这些是经过测试的场景:

这种行为背后的原因可能是什么?解决方案是什么?

//This WORKS
test('testing no headers', () => {
  return axios.get('http://api.fixer.io/latest')
        .then( res => console.log(res) )
});

//This DOES NOT work
test('testing no headers', () => {
  return axios.get('http://localhost:3000/users/4/profile', 
                      {headers:{authorization:`Bearer ${mytoken}`}})
        .then( res => console.log(res) )
});

//...

//Node Terminal
//This WORKS
> axios.get('http://localhost:3000/users/4/profile', 
                   {headers:{authorization:`Bearer ${mytoken}`}})
        .then( res => console.log(res) )

有趣的是,axios 主要使用 XMLHttpRequest,并且 ajax 请求不能跨域访问,所以你的测试失败了,所以你可以让你的代码通过设置 axios 适配器。

原因 axios/defaults.js

 function getDefaultAdapter() {
    var adapter;
    if (typeof XMLHttpRequest !== 'undefined') {
        // For browsers use XHR adapter
        adapter = require('./adapters/xhr');
    } else if (typeof process !== 'undefined') {
        // For node use HTTP adapter
        adapter = require('./adapters/http');   
    }
    return adapter;
 }

解决方案将 axios 适配器更改为 http

import axios from 'axios';
//This WORKS
test('testing with headers', (done) => {
    var path=require('path');
    var lib=path.join(path.dirname(require.resolve('axios')),'lib/adapters/http');
    var http=require(lib);
    axios.get('http://192.168.1.253', {
        adapter: http,
        headers: {
            Authorization: "Basic YWRtaW46bHVveGlueGlhbjkx"
        }
    }).then((res) => {
        expect(res.status).toBe(200);
        done();
    }).catch(done.fail);
});

解决方案更改 package.json

中的 jest testURL
"jest": {
   "testURL":"http://192.168.1.253"
}

然后测试可以通过ajax

访问http
import axios from 'axios';
    //This WORKS
    test('testing with headers', (done) => {
        axios.get('http://192.168.1.253', {
            headers: {
                Authorization: "Basic YWRtaW46bHVveGlueGlhbjkx"
            }
        }).then((res) => {
            expect(res.status).toBe(200);
            done();
        }).catch(done.fail);
    });

Jest 允许您设置安装脚本文件。此文件将在其他所有内容之前被要求,并使您有机会修改测试将在其中进行的环境 运行。通过这种方式,您可以在加载 axios 之前取消设置 XMLHttpRequest,并在提升导入后评估适配器类型。 https://facebook.github.io/jest/docs/configuration.html#setuptestframeworkscriptfile-string

这对我有用:

package.json

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

__tests__/setup.js

global.XMLHttpRequest = undefined;

这可能是 Jest 配置问题。我在 package.json:

中解决了强制 "node" 作为开玩笑的环境

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

查看文档:https://facebook.github.io/jest/docs/configuration.html#testenvironment-string

我通过添加解决了它

axios.defaults.adapter = require('axios/lib/adapters/http');

对于特定的测试用例文件,设置 global.XMLHttpRequest = undefined 或 env=node 导致我的其他测试用例失败。