Jest 返回“网络错误"使用 axios 执行经过身份验证的请求时 [英] Jest returns "Network Error" when doing an authenticated request with axios

查看:36
本文介绍了Jest 返回“网络错误"使用 axios 执行经过身份验证的请求时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这对我来说似乎有点奇怪.我正在尝试使用 Jest 测试实际(即真实网络)请求.

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:

  • 测试没有标头的外部 API (fixer.io) <--- 这有效
  • 测试带有标头的本地 API 服务器<--- 这不起作用
  • 使用来自 node 终端的标头测试相同的本地 API <--- 这有效
  • Test an external API (fixer.io) with no headers <--- This works
  • Test a local API server with headers <--- This does NOT work
  • Test same local API with headers from node terminal <--- This works

这种行为背后的原因是什么?解决办法是什么?

What could be the reason behind this behavior? And what is the solution?

//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通过primary使用了XMLHttpRequest,而ajax请求不能跨域访问,所以你的测试失败了,所以你可以让你的代码通过设置 axios 适配器.

That is funny,that the axios used XMLHttpRequest by primary,and ajax request can't access across domain,so your test failed ,so you can let your code pass by set the axios adapter.

 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

then the test can be access http via ajax

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 执行经过身份验证的请求时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆