【发布时间】:2021-12-07 10:21:16
【问题描述】:
我正在使用axios 从 API 中获取一些用户数据并将它们推送到 vanilla 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.
这个问题最可能的原因是什么?
【问题讨论】:
-
返回 axios.get(
-
罗伯特指出,
fetchUsernames()没有返回声明。
标签: javascript asynchronous async-await axios jestjs