Replies: 4 comments 4 replies
-
I am not sure what is the proper answer to this, but I ended up writing a custom matcher: import { randomUUID as uuid } from 'node:crypto';
import { serializeError } from 'serialize-error';
import { match } from 'tcompare';
import { beforeEach, expect } from 'vitest';
beforeEach(() => {
globalThis.TEST_RUN_ID = uuid();
});
expect.extend({
toMatchErrorObject(received, expected) {
const result = match(serializeError(received), expected);
return {
message: () =>
`Expected errors to match:\n${result.diff}\nReceived:\n${JSON.stringify(
serializeError(received),
null,
2,
)}`,
pass: result.match,
};
},
}); This produces a nice error when things don't go according to plan: Error: Expected errors to match:
--- expected
+++ actual
@@ -1,3 +1,3 @@
Object {
- "message": "Query violates a check integrity constraint.a",
+ "message": "Query violates a check integrity constraint.",
}
Received:
{
"cause": {
"length": 369,
"name": "error",
"severity": "ERROR",
"code": "23514",
"detail": "Failing row contains (1, 1, 2, DEBIT, 0.00000000, 2023-10-26 15:42:18.202113+00, 2023-10-26 15:42:18.202113+00).",
"schema": "public",
"table": "ledger_transaction_entry",
"constraint": "ledger_transaction_entry_amount_positive",
"file": "execMain.c",
"line": "1934",
"routine": "ExecConstraints",
"message": "new row for relation \"ledger_transaction_entry\" violates check constraint \"ledger_transaction_entry_amount_positive\""
},
"constraint": "ledger_transaction_entry_amount_positive",
"column": null,
"table": "ledger_transaction_entry",
"notices": [],
"name": "CheckIntegrityConstraintViolationError",
"message": "Query violates a check integrity constraint."
} |
Beta Was this translation helpful? Give feedback.
-
Your solution looks correct, but the fact that it doesn't show a diff looks like a bug. |
Beta Was this translation helpful? Give feedback.
-
Raising a related discussion to improve error assertions: #5697 (particularly focusing on asserting |
Beta Was this translation helpful? Give feedback.
-
I also would like a matcher like this. My use case is testing that a Remix
|
Beta Was this translation helpful? Give feedback.
-
I need to write a check that effectively checks values of error properties. In ava I was able to do it in such a way:
Whereas with Vitest it seems I am only able to assert what is the top level error message.
Looks like you can do this:
but the error when it doesn’t match is so useless, e.g.
The error it produces is:
I would expect object to be dumped showing what didn't match.
Beta Was this translation helpful? Give feedback.
All reactions