【问题标题】:Unit testing async/await javascript with mocha and chai使用 mocha 和 chai 对 async/await javascript 进行单元测试
【发布时间】:2021-03-20 07:33:33
【问题描述】:

大家好,我目前正在研究这个异步函数并为此编写单元测试,但它不起作用它说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 来完成它,所以我是新手。我真的很想看看这是怎么做到的,所以提前谢谢:)

【问题讨论】:

标签: javascript node.js unit-testing mocha.js chai


【解决方案1】:

尽管您在上面给出了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;
}

【讨论】:

    猜你喜欢
    • 2018-01-02
    • 2021-09-14
    • 2018-12-30
    • 2014-11-25
    • 2021-09-27
    • 2017-02-18
    • 1970-01-01
    • 2015-05-16
    • 2019-02-14
    相关资源
    最近更新 更多