Yes, the idea is almost that same (I will explain at the end a remark on the statement of the question).
In case, as you are testing an error, you can nay occur (due to some error), it is important that you tell your test framework - like Jest, in this case - how many assertions are being made. For this, some API like the expect.assertions
in Jest should be used.
So, if the number of assertions is different from the number you provided, the test will give error and you will know that there is something wrong.
This kind of assertion ensures the integrity of your test, which is in fact testing the behavior of your code.
However, it is not always necessary to inform the number of assertions to be made within a test block, since usually when you test something wrong, an error will be released by the normal behavior of the language itself (such as a TypeError
in Javascript when trying to invoke a method that has not been correctly implemented in an object).
In this case, as no syntax error or other error recognizable by the test framework itself or language, you need to explicitly inform that you expect a behavior. So, if the behavior does not occur, you will have an assertion that has not been executed and you will know it. Without this explicit number, you will be beaten.
[...] So, the use of assertions is only to affirm to Jest that it is only this result that interests us, doing any other return from Promise is given as a test error? For example, if Promise is solved, the test needs to be error, since we expect only one result, which is something with the string error. [...]
I do not believe that the above is correct, since the purpose of defining the explicit number of assertions is not to guarantee a specific behavior, but to ensure that an amount N of assertions are executed.
As we have seen above, if an assertion is not executed, the testing framework will have no way of knowing if something actually occurred (since an error, for example, may not have been released). Thus, in view of the fact that an assertion is not executed nay will fail the test, we need to clarify the amount of assertions that should be made in case one of them is in a code snippet that can not be executed in the event of some incorrect behavior.
Hello, Luiz Felipe. So the use of
assertion
is to inform how often I wait for a certain behavior? In the case of the doc example I inform that I expect an error to be returned with the string 'error' only once. What if I informed aexpect.assertions(2);
in that same code? I would be telling Jest that I expect that return twice?– V. Rodrigues
Yes, but it’s not limited to that, you’re saying that within that testing block two assertions must be made, no matter where.
– Luiz Felipe