[英]Unit testing async/await javascript with mocha and chai
Hey guys so I am currently working on this async function and writing unit test for this but it is not working it says AssertionError: expected undefined to equal 'Everytime I think of coding, I am happy'
this is my code for the function:嘿伙计们,所以我目前正在研究这个异步 function 并为此编写单元测试,但它不起作用,它说
AssertionError: expected undefined to equal 'Everytime I think of coding, I am happy'
这是我的 function 代码:
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();
And here is my unit test for it:这是我的单元测试:
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")
})
})
})
This is the first time I write unit test and I am trying to do it with async func so I am new to it.这是我第一次编写单元测试,我试图用 async func 来做,所以我是新手。 I really want to see how this is done so Thanks in advance:)
我真的很想看看这是怎么做到的,所以提前谢谢:)
Although you have given funcFour()
above and trying to test flirtFour()
below, I am assuming they are the same.尽管您在上面给出了
funcFour()
并尝试在下面测试flirtFour()
,但我假设它们是相同的。 Now flirtFour()
doesn't return anything as of now.现在
flirtFour()
没有返回任何东西。 You need to return the response
from that function.您需要从该 function 返回
response
。 By default, the returned value is undefined
.默认情况下,返回值为
undefined
。 Also remember that whatever you return from the async
function gets wrapped into a Promise itself.还要记住,无论您从
async
function返回什么,都会被包装到 Promise 本身中。 So you're actually returning a Promise like so:-因此,您实际上是在返回Promise ,如下所示:-
return Promise.resolve(undefined)
. return Promise.resolve(undefined)
。
If you simply return response
that will automatically be treated as如果您只是返回将自动被视为的
response
return Promise.resolve(response)
which is probably what you need.这可能是你需要的。
So change your funcFour()
to the following:-因此,将您的
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.