[英]How do I test an async axios call from a function that's defined inside an ES6 class?
我想測試一個類中的異步函數,該函數使用 axios 進行 Web 服務器調用,但我收到一條錯誤消息
Received promise rejected instead of resolved
Rejected to value: [TypeError: errorHandler is not a function]
我進行調用的實際代碼如下所示:
import axios from 'axios';
export default class MyClass{
constructor(config){
this.config = config;
}
async getUsers(url, params, successHandler, errorHandler) {
return axios.post(url, params)
.then(resp => this.handleAPIResponse.call(this, resp, successHandler, errorHandler))
.catch(error => errorHandler);
}
}
我的測試文件看起來像這樣
import MyClass from './mycode.js';
import axios from 'axios';
jest.mock('axios');
beforeEach(() => {
instance = new MyClass({ env: 'prod' });
});
afterEach(() => {
jest.clearAllMocks();
});
const mockResponseData = jest.fn((success, payload) => {
return {
data: {
result: {
success,
payload
}
}
};
});
test('should return all the users', async () => {
const successHandler = jest.fn();
const errorHandler = jest.fn();
axios.post.mockImplementationOnce(() => {
return Promise.resolve({
data:['John Doe', 'Charles']
});
});
const response = await myClass.getUsers('url', {}, successHandler, errorHandler);
console.log(response); // This logs undefined
expect(successHandler).toHaveBeenCalledTimes(1);
});
另外,我只想澄清一下,我的src
目錄下有一個__mocks__
文件夾,其中有一個名為axios.js
的文件,我在其中axios
了每個axios
方法。 它看起來像這樣:
export default {
post: jest.fn(() => Promise.resolve({ data: {} }))
};
提前致謝。
Jest 文檔明確指出:
當我們需要在我們的測試,模塊,顯式調用
jest.mock('./moduleName')
是必需的。
所以你需要打電話
jest.mock('axios')
為了使用你的__mocks__/axios.js
我認為問題在於您的課程使用的是真實的包,而您的規范文件使用的是模擬的。
您必須直接在您的規范文件或setupTests.js
文件中模擬它:
import axios from 'axios'
jest.spyOn(axios, 'post')
.mockImplementationOnce(...)
編輯:也許嘗試調用jest.mock('axios');
在您的步驟文件之上。 這有點重復,但有時 Jest 只需要它來正確模擬。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.