'Is it wrong to use await within jest's expect?
I read the official jest documentation on async/await as well as numerous blog posts dealing with the topic. All are describing different ways of awaiting a value on which assertions are made as well as waiting for the test function to complete. None of them included the following pattern, however I don't see why it should cause trouble: Assume I have a
const getValue: () => Promise<string>
and that I'm testing it with
test("await in expect", async () => {
expect(await getValue()).toBe("b")
})
I can't reproduce the issue with an implementation like
const getValue = () => new Promise((resolve) => {
setTimeout(() => {
resolve("b")
}, 4000)
})
however I'm experiencing about 20% fails of an integration test where getValue runs queries against a real database because afterAll function is called early and terminates the connection.
I'm aware that I can overcome this with resolves and other use of await or done or else, e.g.
test("await in expect", async () => {
await expect(getValue()).resolves.toBe("b")
})
and I already managed to overcome the issue in my real world integration test with this approach.
However, I'd like to broaden my understanding of what's going on and what I'm doing when using await inside expect().
I'm using Jest 27.
Solution 1:[1]
There's a good reason why one should create real reproducers for issues and questions: The issue might turn out to be something completely different.
In this case the TypeORM Repository.save promise apparently returns before the saved instance is flushed into the database or cache or whatever which is queried by Repository.find.
I might investigate further or just go with a 100ms sleep after save. And yes, you can quote that in yet another blog post about why ORMs are troublesome.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kalle Richter |
