I try to do this:
it('should throw an error', async ()=> {
expect.assertions(1);
try {
await processor({}, MODULE_CONFIG)
}
catch (e) {
expect(e).toBe("[TypeError: Cannot read properties of undefined (reading 'match')]")
}
});
but it gives me this error:
I tried toMatch
like in the docs, but it also give an error (one that seems even worse)
I tried using rejects.tobe
instead, but i get the same error:
CodePudding user response:
Your problem is with what you are trying to assert
I'm assuming that you are throwing an error from processor
If you are, and you are asserting what that error is, keep in mind that typeof e === object
, not string
For example:
function iThrownAnError() {
throw new Error("ups");
}
describe("test a function that throws an error", () => {
it("catches an error as expected", () => {
try {
iThrownAnError();
} catch (e) {
console.log(typeof e); // logs object
console.log(typeof "ups"); // logs string
// the test pass
expect(e).toStrictEqual(new Error("ups"));
// the test would fail
// Expected: "ups"
// Received: [Error: ups]
expect(e).toStrictEqual("ups");
}
});
});
CodePudding user response:
The best answer I found seems to be getting the message
property from the error (which is essentially just the error as a string), and comparing that.
expect(e.message).toBe("Cannot read properties of undefined (reading 'match')")