enzymejs / enzyme

JavaScript Testing utilities for React
https://enzymejs.github.io/enzyme/
MIT License
19.96k stars 2.01k forks source link

Function test within a promise does not recognize toHaveBeenCalledTimes #2555

Closed juliGer closed 2 years ago

juliGer commented 2 years ago

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

Screenshot_20220402_144952

Component

Screenshot_20220402_144856

Result

Screenshot_20220402_145016

But if I change the line of this.client.get() outside of the then it does recognize the call in the test.

Screenshot_20220402_145131

Result

Screenshot_20220402_145151

Does anyone know how to make this work? Thanks and greetings!

ljharb commented 2 years ago

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.

juliGer commented 2 years ago

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!