Friday, 2 August 2019

jest expect, and combine with another expect, or toHaveBeenCalledWith with.

doc:

https://jestjs.io/docs/en/expect#expectstringcontainingstring


if you have an error logged by console.error(e), then you want to jest test it.

you can
const e = new Error("my e");
console.error(e)

solution 1:
expect(console.error).toHaveBeenCalledWith(e);

solution 2:
expect(console.error).toHaveBeenCalledWith(expect.objectContaining(
{message: "my e"}
));


bad solution:
expect(console.error).toHaveBeenCalledWith(expect.stringContaining("my e"));

expect(console.error).toHaveBeenCalledWith(expect.stringMatching("/my e/"));
because it is not called with object, even you think it printed out a string which has your string, but it is an object, not string.....

string only work with this:

expect('abc').toEqual(expect.stringContaining('b'));

No comments:

Post a comment