我正在使用 jest 來測驗 axios API 呼叫。模擬 API 不會決議或回傳值,也不會呼叫模擬函式。這是我的 API 呼叫和測驗代碼。
這是具有 postData 功能的基本服務檔案
import axios from 'axios';
const API_ENDPOINT = process.env.REACT_APP_API_ENDPOINT;
function setHeader(contentType:string, token:string|undefined) {
return {
'Accept': 'application/json',
'Content-Type': contentType,
'Authorization': `Bearer ${token}`,
};
}
async function postData(path:string, contentType:string, token:string|undefined,
payload:FormData | Record<string, any> | string) {
return axios({
method: 'post',
url: `${API_ENDPOINT}${path}`,
headers: setHeader(contentType, token),
data: payload,
});
}
export {postData}
這是我嘗試過的測驗檔案代碼。
import '@testing-library/jest-dom';
import axios from 'axios';
import confirmProfile from '../../apis/onboard/confirmProfile';
jest.mock('axios');
const mockAxios=axios as jest.Mocked<typeof axios>;
const VALID_TOKEN='eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzZXNzaW9uIjoicmRjZDhpbXduOXl0YjZ5eTRrN3I4NnJsb3RjcnZ0cHkiLCJuYmYiOjE2NTI2NzYyNTguMzcwNTUyOCwiaXNzIjoiZ296ZWFsIn0.IR1hNOZPY4rcrykJgzrGkgfJM9vJNuveG-KS8BYaxnI';
it("Confirm profile original file with valid params",async ()=>{
const res={confirmProfileData: { isSuccess: false },
apiError: undefined,
}
mockAxios.post.mockResolvedValueOnce(res);
const response = await confirmProfile(VALID_TOKEN);
console.log('profile',response);
expect(mockAxios.post).toHaveBeenCalledTimes(1);
expect(response).toEqual(res);
})
測驗結果
FAIL src/__tests__/apis/Testing.test.ts
? Confirm profile original file with valid params (10 ms)
● Confirm profile original file with valid params
expect(jest.fn()).toHaveBeenCalledTimes(expected)
Expected number of calls: 1
Received number of calls: 0
27 | const response = await confirmProfile(VALID_TOKEN);
28 | console.log('profile',response);
> 29 | expect(mockAxios.post).toHaveBeenCalledTimes(1);
| ^
30 | expect(response).toEqual(res);
31 | })
32 |
at Object.<anonymous> (src/__tests__/apis/Testing.test.ts:29:28)
console.log
profile { confirmProfileData: { isSuccess: true }, apiError: undefined }
at Object.<anonymous> (src/__tests__/apis/Testing.test.ts:32:1)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 1.857 s, estimated 3 s
未呼叫模擬函式且模擬值未決議或記錄
uj5u.com熱心網友回復:
問題是由于您的代碼沒有直接在 axios 模塊實體上呼叫 post 函式,而是通過 json 引數隱式執行它,而您的測驗模擬正在尋找直接 axios.post 呼叫。有 2 種方法可以解決此問題。
1 . 將隱式后呼叫更改為顯式呼叫:
從:
axios({
method: 'post',
url: `${API_ENDPOINT}${path}`,
headers: setHeader(contentType, token),
data: payload,
})
到:
axios.post(`${API_ENDPOINT}${path}`, payload, { headers: setHeader(contentType, token) })
2.在測驗套件設定中模擬 axios 后呼叫:
從:
jest.mock("axios")
到
jest.mock("axios", () => {
const expectedResponse = JSON.stringify({
"access_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6ImMxZDY2OTF",
"issued_token_type": "token-type:access_token",
"token_type": "Bearer",
"expires_in": 3600,
"scope": "consumer_profile:read:"
});
return () => new Promise((resolve) => resolve(expectedResponse));
})
這將通過部分模擬來模擬隱式后呼叫,但是您將無法直接訪問該post方法,因此您將無法專門監聽它的呼叫。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/477570.html
上一篇:我在哪里可以找到可以在XSLFO中為可訪問檔案放入角色屬性的所有值?
下一篇:抽象類中的C#Moq方法
