簡體   English   中英

使用 axios 執行經過身份驗證的請求時,Jest 返回“網絡錯誤”

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

這對我來說似乎有點奇怪。 我正在嘗試使用 Jest 測試實際(即 real.network)請求。

這些是經過測試的場景:

  • 測試一個沒有標題的外部 API (fixer.io) <--- 這有效
  • 使用標頭測試本地 API 服務器<--- 這不起作用
  • 使用來自node終端的標頭測試相同的本地 API <--- 這有效

這種行為背后的原因可能是什么? 解決方案是什么?

//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) )

它可能是Jest配置問題。 我解決了強制“node”作為package.json中的jest環境:

“jest”:{“testEnvironment”:“node”}

請參閱docs: https//facebook.github.io/jest/docs/configuration.html#testenvironment-string

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;

有趣的是,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);
    });

我通過添加來解決它

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

對於特定的測試用例文件,因為設置global.XMLHttpRequest = undefined或env = node導致我的其他測試用例失敗。

我在 Next.js 項目上工作,在這些項目中我同時進行了前端和后端測試,並且將testEnvironment設置為“節點”不起作用。

所以我將jest.config.js配置為

testEnvironment: 'jest-environment-jsdom',

並添加

/**
 * @jest-environment node
 */

所有后端測試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM