我強烈懷疑這與使用異步呼叫的 api 有關,但據我所知,我在所有正確的地方都有“等待”。
進行呼叫的單元測驗:
const { expect } = require('@jest/globals');
const { getWorkerId } = require('../api');
describe("Workers api", () => {
test("it should return a status of 200", async () => {
let response = await getWorkerId(21882000)
expect(response.status).to.equal('200')
});
});
和 api 本身:
const axios = require('axios');
const getWorkerId = async (id) => {
await axios.get(`http://localhost:8080/v1/workers/${id}`)
.then(function (response) {
console.log(response.status);
return response;
})
.catch(function (error) {
console.log('Error number: ', error.errno);
console.log('Error code: ', error.code);
return error;
})
};
module.exports = { getWorkerId };
'console.log(response.status)' 行按預期輸出'200',如果我將代碼更改為顯示'response',肯定就在那里。然而,我的單元測驗的期望呼叫回傳:'TypeError: Cannot read property 'equal' of undefined'.x
uj5u.com熱心網友回復:
與 JS 中的 async/await 和 Promises 混淆是很常見的。我會在這里盡量簡潔,但這是一個很大的話題,有很多細節,所以請耐心等待!
首先,當使用 async/await 時,不需要使用.then(). 關鍵字將await(從字面上看)等待 Promise 被決議,并獲得它的回傳值。同樣,.then()將獲得 promise 的決議值,這是您收到的引數,在您的情況下,它response是.then().
因此,await和.then()以類似的方式作業,您甚至可以將它們一起使用,如下所示:
const response = await axios.get('https://jsonplaceholder.typicode.com/todos/1').then((data) => {
console.log(data)
return data
}).catch((err) => {
console.log(err)
return err
})
console.log(response.status) // Output is 200
上面發生的事情是await獲得 的回報.then(),并將其分配給response。所以,如果你使用 async/await 和.then(),你應該有一個變數來接收回傳的值.then(),這樣你就可以在作用域之外使用它。
但是,在您的情況下,我們有以下內容:
const getJsonPlaceholder = async (id) => {
await axios.get(`https://jsonplaceholder.typicode.com/todos/${id}`).then((data) => {
console.log(data)
return data
}).catch((err) => {
console.log(err)
return err
})
}
const response2 = await getJsonPlaceholder()
console.log(response2.status)// Output is "Cannot read property 'status' of undefined"
發生的事情是await接收回傳的值.then(),將其分配給任何內容,并且函式getJsonPlaceholder回傳 undefined,這是 JS 中不回傳任何內容的函式的默認值。
在這里,您可以找到JS中 async/await.then()和.catch()用例的精彩總結。
And, finally, for your test case to pass, drop the .then(), assign the returned value of the axios request to a variable, and return this variable on the function getWorkerId, this should be enough!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/443523.html
