Reputation: 4392
function sum(a,b) { return a+b;}
it("testing snapshot with sum",()=>{
expect(sum(1,2)).toMatchSnapshot();
})
How does the above test through error in case the test returns value other than 3 at first snapshot itself? I guess it compares relatively but I am not sure if it can be used where we know what's the exact value gonna be.
Upvotes: 1
Views: 142
Reputation: 45850
Just to be complete:
If Jest runs a snapshot test and no snapshot exists yet, it will create one. From the docs:
On subsequent test runs Jest will simply compare the rendered output with the previous snapshot. If they match, the test will pass. If they don't match, either the test runner found a bug...or the implementation has changed and the snapshot needs to be updated.
Note that
The snapshot artifact should be committed alongside code changes, and reviewed as part of your code review process.
Snapshot testing is most commonly used for UI code, but that doesn't mean it can only be used for UI code.
For the test you are describing, the first time the test runs it will create the snapshot with the value 3
.
It is up to you, as the developer, to make sure that value is correct and to check the snapshot in with your source code.
Ultimately that is the same process as checking that you passed the correct value of 3
into something like .toBe(3)
and checking that assertion into your source code.
So yes, that is a valid way to test the function being tested.
Having said that, there is a lot more overhead for toMatchSnapshot
than for something like toBe
so for a simple test like this it makes sense to just use .toBe(3)
instead of .toMatchSnapshot()
.
Snapshot testing is most useful for complex values like UI that would bloat your test files if they were included inline and are challenging to update accurately. With snapshot testing they are stored in a separate file and updates can be made easily by telling Jest
to update the snapshot once the updated value has been verified to be correct.
Upvotes: 1
Reputation: 13983
Snapshot testing with toMatchSnapshot()
is used to test the rendered UI, that is, the HTML of your components.
If you want to do a unit test and test the output of a function, you can use matchers suchs as toEqual
, see this doc about Jest matchers.
In your case:
function sum(a, b) { return a + b; }
it("testing snapshot with sum", () => {
expect(sum(1, 2)).toEqual(3);
})
Upvotes: 1