'It there a jest matcher that works like toEqual, but treats null and undefined as equal values?
I have an API that does not omit JSON serialization for fields with "empty" (null, none, nil) values and returns all of them as "fieldName": null. I have typed DTOs in testing code (TypeScript), and I would like to make such fields as optional (?) and leave them undefined in many places. Unfortunately (for me) jest's toEqual() treats undefined (values in testing code) and null (values from API) as different values.
My current solution is to use union types like string | null, but it is pretty verbose, because I have to always initialize those fields.
I checked jest's reference and did not find an "off-the-shelf" solution. So, creation a custom matcher is the only way to solve my problem?
Note: I can't change policy of serialization in API.
Solution 1:[1]
expect(null).toBe(undefined) fails!
Basically what you have is that sometimes after evaluating an object you have null in one side and undefined in the other
I tried to use other jest methods as toEqual but symply didn't work.
My solution
expect(null == undefined).toBe(true)
Solution 2:[2]
You can create any matches that you want with Jest. For example this might be what you need exactly:
beforeAll(function () {
expect.extend({
toBeMyEqual(received, expected) {
const pass = this.equals(received, expected) ||
(received === null && received === undefined) ||
(received === undefined && received === null);
if (pass) {
return {
message: () =>
`expected ${received} not to equal ${expected}`,
pass: true,
};
} else {
return {
message: () =>
`expected ${received} to equal ${expected}`,
pass: false,
};
}
}
})
})
test('should pass', () => {
expect(null).toBeMyEqual(undefined);
})
You can probably add this to some setup script, I only added it in a beforeAll for testing's sake.
And here is the relevant documentation:
Solution 3:[3]
after a long search, the best solution for this dilemma is to use
.toBeTruthy, in case value is null or undefined. details here
However, keep in mind that it will fail with empty strings and with false booleans
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Carlos |
| Solution 2 | ziale |
| Solution 3 | WadeeSami |
