简体   繁体   中英

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 await ing 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, eg

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM