Skip to content

Commit 7b4f651

Browse files
committed
Add areErrorsEqual equality tester
- This was done to make sure `toHaveBeenCalledWith` will fail if we pass in the wrong Error constructor. For example the assertion will now fail if we pass in an `Error` instead of a `TypeError`.
1 parent 0b01841 commit 7b4f651

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

packages/toolkit/vitest.setup.ts

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,46 @@ vi.stubGlobal('fetch', nodeFetch)
55
vi.stubGlobal('Request', Request)
66
vi.stubGlobal('Headers', Headers)
77

8+
/**
9+
* Compares two values to determine if they are instances of {@linkcode Error}
10+
* and have the same {@linkcode Error.name | name}
11+
* and {@linkcode Error.message | message} properties.
12+
*
13+
* @param actualError - The actual error to compare.
14+
* @param expectedError - The expected error to compare against.
15+
* @returns `true` if both values are instances of {@linkcode Error} and have the same {@linkcode Error.name | name} and {@linkcode Error.message | message}.
16+
*
17+
* @example
18+
* <caption>#### __Pass: The actual error is an instance of `TypeError` with the same `message` ✔️__</caption>
19+
*
20+
* ```ts
21+
* expect(consoleErrorSpy).toHaveBeenLastCalledWith(
22+
* TypeError('endpointDefinition.queryFn is not a function'),
23+
* )
24+
* ```
25+
*
26+
* @example
27+
* <caption>#### __Fail: The actual error is a `TypeError`, which is more specific than the expected generic `Error` ❌__</caption>
28+
*
29+
* ```ts
30+
* expect(consoleErrorSpy).toHaveBeenLastCalledWith(
31+
* Error('endpointDefinition.queryFn is not a function'),
32+
* )
33+
* ```
34+
*
35+
* @internal
36+
*/
37+
const areErrorsEqual = (actualError: unknown, expectedError: unknown) => {
38+
if (actualError instanceof Error && expectedError instanceof Error) {
39+
return (
40+
actualError.name === expectedError.name &&
41+
actualError.message === expectedError.message
42+
)
43+
}
44+
}
45+
46+
expect.addEqualityTesters([areErrorsEqual])
47+
848
beforeAll(() => {
949
server.listen({ onUnhandledRequest: 'error' })
1050
})

0 commit comments

Comments
 (0)