首页 > 解决方案 > 使用 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 来做,所以我是新手。我真的很想看看这是怎么做到的,所以提前谢谢:)

标签: javascriptnode.jsunit-testingmocha.jschai

解决方案


尽管您已在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;
}

推荐阅读