Function test within a promise does not recognize toHaveBeenCalledTimes
juliGer opened this issue · 2 comments
Hello! I have a problem with the development of a test and I am not able to solve it.
I am trying to test a login which I was able to mock the fetch function and another function that I need but this last one is not recognizing the call when I try to do
expect(functionGet).toHaveBeenCalledTimes(1)
But this is weird because if I add a console.log in the code I see the response of the mock function below I leave the code with which it fails
Test Fail
Component
Result
But if I change the line of this.client.get() outside of the then it does recognize the call in the test.
Result
Does anyone know how to make this work? Thanks and greetings!
Yes, this is a normal misunderstanding of how asynchrony works in JS.
In order for your test to make an assertion about client.get, the test has to "know" what to wait for. In other words, unless the test can access the promise created by the .then
- that resolves after the .get is called - it's simply not possible to test this.
This isn't unique to enzyme, react, jest, or fetch, it's just how async works in JS.
Yes, this is a normal misunderstanding of how asynchrony works in JS.
In order for your test to make an assertion about client.get, the test has to "know" what to wait for. In other words, unless the test can access the promise created by the
.then
- that resolves after the .get is called - it's simply not possible to test this.This isn't unique to enzyme, react, jest, or fetch, it's just how async works in JS.
Ah I understand thank you very much!