我正在使用axios從 API 獲取一些用戶資料并將它們推送到普通 JS 檔案中的陣列中,如下所示:
export async function fetchUsernames() {
let usernames = [];
axios.get("https://jsonplaceholder.typicode.com/users").then((users) => {
for (let user of users.data) {
usernames.push(user["username"]);
}
return usernames;
});
}
問題是,即使當我將它與 react 連接時它在我的前端正常作業,我的jest測驗塊總是undefined作為回傳值,即使我使用 async/await。這是我的測驗塊:
test('Usernames get fetched properly', async () => {
const usernames = await fetchUsernames();
expect(usernames).toBe(expect.arrayContaining(['Brett']));
});
這是我收到的錯誤訊息:
× Usernames get fetched properly (17 ms)
● Usernames get fetched properly
expect(received).toBe(expected) // Object.is equality
Expected: ArrayContaining ["Brett"]
Received: undefined
12 | test('Usernames get fetched properly', async () => {
13 | const usernames = await fetchUsernames();
> 14 | expect(usernames).toBe(expect.arrayContaining(['Brett']));
| ^
15 | });
at Object.<anonymous> (src/App.test.js:14:21)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 passed, 2 total
Snapshots: 0 total
Time: 4.038 s
Ran all test suites related to changed files.
這個問題背后的原因最有可能是什么?
uj5u.com熱心網友回復:
如下更改 fetchUser 函式。
async function fetchUsernames() {
let usernames = [];
let users = await axios.get("https://jsonplaceholder.typicode.com/users");
for (let user of users.data) {
usernames.push(user["username"]);
}
return usernames;
}
這將回傳用戶名陣列。
test('Usernames get fetched properly', async () => {
const usernames = await fetchUsernames();
expect(usernames).toBe(expect.arrayContaining(['Brett']));
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/376058.html
標籤:javascript 异步 异步等待 公理 玩笑
下一篇:異步函式中的回傳值為空
