![](/img/trans.png)
[英]Jest returns "Network Error" when doing an authenticated request with axios
[英]jest axios test passes with advisory Network Error
我有一個實用程序 class,它使用 axios 來執行簡單的 REST 調用。 在編寫一個笑話單元測試時,雖然測試通過了,但我似乎得到了一個咨詢錯誤:
C:/home/dev/node_modules/axios/lib/core/createError.js:16
var error = new Error(message);
Error: Network Error
at createErrorC:/home/dev/node_modules/axios/lib/core/createError.js:16
config: {
// ....
header: { Accept: 'application/json, text/plain, */*' },
withCredentials: true,
responseType: 'json',
method: 'get',
url: 'http://mock.rest.server.com:1234/rest/user/data/adam',
data: undefined
},
request: XMLHttpRequest {},
response: undefined,
isAxiosError: true,
toJSON: [Function: toJSON]
實用程序.ts
import axios, { AxiosResponse } from 'axios'
axios.defaults.withCredentials = true;
axios.defaults.responseType = 'json';
export class UserUtils {
public getUserConfig(userName: string): Promise<AxiosResponse> {
if(!userName) {
return;
}
return axios.get('http://mock.rest.server.com:1234/rest/user/data/' + userName);
}
}
實用程序.test.ts
import axios from 'axios';
import { UserUtils } from '../../utility';
describe("Utility test", () => {
const utils = new UserUtils();
jest.mock('axios', () => {
return {
post: jest.fn(),
get: jest.fn()
}
}
// clear all mocks
beforEach(() => {
jest.clearAllMocks();
jest.restoreAllMocks();
});
test("get user data",() => {
jest.spyOn(axios, 'get');
utils.getUserConfig('adam')
.then(repsonse => {
expect(axios.get).toHaveBeenCalledWith('http://mock.rest.server.com:1234/rest/user/data/adam');
});
});
});
也許這個線程可以幫助你: https://stackoverflow.com/a/51654713/20293448
就個人而言,我喜歡使用 jest manual mocks ( docs )
在我的項目中,我有:
// src/__mocks__/axios.ts
import axios from 'axios';
const mockAxios = jest.genMockFromModule<typeof axios>('axios');
// this is the key to fix the axios.create() undefined error!
mockAxios.create = jest.fn(() => mockAxios);
// eslint-disable-next-line import/no-default-export
export default mockAxios;
// src/.../test.ts
import mockAxios from 'axios';
const mockedPost = mockAxios.post as jest.Mock;
beforeEach(() => {
jest.clearAllMocks();
});
...
expect(mockedPost).toHaveBeenCalledWith(route, payload);
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.