Gustavo F.
Gustavo F.

Reputation: 125

Coverage in Jest doesn't cover branches

I am trying to create a unit test for my API, but I don't get 100% coverage in jest. I have created every possible test that I could think, but the coverage report still says that I have not tested all statements, branches and lines. Can someone help me? This is happening in lines 28, 29, 32 and 33

enter image description here

Upvotes: 2

Views: 1611

Answers (1)

Mr. Hedgehog
Mr. Hedgehog

Reputation: 2885

According to my calculations, to fully cover execute function, you will need at least this 5 tests:

  • When this.classRepository.getAll() resolves with empty array
  • When this.classRepository.getAll() resolves with one item,
    • when this.commentsRepository.getLastCommentForClass() resolves with a comment
    • when this.commentsRepository.getLastCommentForClass() resolves without a comment
    • when this.commentsRepository.getLastCommentForClass() rejects
  • When this.classRepository.getAll() rejects

As a sanity check, I'd try also check when this.classRepository.getAll() resolves with more than one item, since Promise.all rejects if at least one promise inside rejects. In case of two items it will 9 tests instead of 3, so it is better to cover map function separately and use like black box here.

Next sanity check would be to resolve your promises with unexpected data. It is important, because you don't have any error handling here, and even if you handle errors outside with .catch it is better to supply proper rejections (for example have error for unexpected stuff and error for expected stuff).

Now, I explain how I calculated this.

I drew a model of your function and counted how many paths there is. I excluded unimportant in my opinion paths (for example repetition in map function), and in the end got this tests. Here is the model:

enter image description here

Upvotes: 3

Related Questions