javascript - 使用 mocha 和 chai 对 async/await javascript 进行单元测试
问题描述
嘿伙计们,所以我目前正在研究这个异步函数并为此编写单元测试,但它不起作用它说AssertionError: expected undefined to equal 'Everytime I think of coding, I am happy'
这是我的函数代码:
async function funcFour() {// async automatically returns a promise
let result = new Promise((resolve) => {// returns a new promise named result
setTimeout(() => {
resolve(`Everytime I think of coding, I am happy`);//resolve happens after three seconds
}, 1500)
});
const response = await result;//closing resolve of new promise
console.log(response);//console.logging response of new promise
} funcFour();
这是我的单元测试:
describe("flirtFour()", () => {
it("Should return Everytime I think of coding, I am happy", async function () {
return flirtFour().then(result => {
expect(result).to.equal("Everytime I think of coding, I am happy")
})
})
})
这是我第一次编写单元测试,我试图用 async func 来做,所以我是新手。我真的很想看看这是怎么做到的,所以提前谢谢:)
解决方案
尽管您已在funcFour()
上面给出并尝试在flirtFour()
下面进行测试,但我假设它们是相同的。现在flirtFour()
不返回任何东西。您需要response
从该函数返回。默认情况下,返回值为undefined
. 还要记住,从函数返回async
的任何内容都会被包装到 Promise 本身中。所以你实际上是在像这样返回一个Promise :-
return Promise.resolve(undefined)
.
如果您只是返回response
,它将自动被视为
return Promise.resolve(response)
这可能是你需要的。
因此,将您更改funcFour()
为以下内容:-
async function funcFour() {// async automatically returns a promise
let result = new Promise((resolve) => {// returns a new promise named result
setTimeout(() => {
resolve(`Everytime I think of coding, I am happy`);//resolve happens after three seconds
}, 1500)
});
const response = await result;
return response;
}
推荐阅读
- regex - 正则表达式替换 Google 表格中的论坛以替换多行中的多个匹配项
- postgresql - 在事务期间检索 Postgres 数据库的 LSN
- sql - Impala SQL 将多个值合并为 1
- python - 将不同数据框中的数据添加到excel
- flutter - How To set input and output data string tensorflow lite in flutter
- mongodb - Spring data MongoDB change stream with multiple application instances
- reactjs - MUI v5:带有 StyledBadge 图标的 BottomNavigationAction?
- eclipse - Duplicate method in call() mcp
- python - 简单的 Python 摇滚,纸,剪刀游戏需要帮助
- mysql - Is this database schema for reservation and incidentals billings correct?