I have trouble checking whether promise rejects with error in Jest test.
(post Jest 20 version:)
test("Rejects on error", () => {
expect.assertions(1);
return expect(promiseHttpsGet(null)).rejects.toBeInstanceOf(Error);
});
(pre Jest 20 version)
test("Rejects on error", () => {
expect.assertions(1);
return promiseHttpsGet(null).catch((err) => {
expect(err).toBeInstanceOf(Error);
});
});
I have tried both versions but Jest test fails with:
Expected value to be an instance of:
"Error"
Received:
[Error: connect ECONNREFUSED 127.0.0.1:443]
Constructor:
"Error"
And the promise returning function is:
function promiseHttpsGet(url) {
return new Promise((resolve, reject) => {
https
.get(url, (response) => {
let responseBody = "";
if (response.statusCode !== 200) {
reject(response.statusCode);
}
response.setEncoding = "utf8";
response.on("data", (data) => {
responseBody += data;
});
response.on("end", () => {
resolve(responseBody);
});
})
.on("error", (error) => {
reject(error);
});
});
}
Any leads how to solve it? Thanks.
In this case, the test will fail because the WebDriver could not find the element. In this case, StaleElementReferenceException will be thrown.
Jest function toHaveBeenCalledWith to ignore object order. 3. Jest to match every object in array.
With Jest's Object partial matching we can do: test('id should match', () => { const obj = { id: '111', productName: 'Jest Handbook', url: 'https://jesthandbook.com' }; expect(obj). toEqual( expect. objectContaining({ id: '111' }) ); });
From Jest 23 onwards toThrow
matcher can be used for promise returning functions.
test("Rejects on error", () => {
expect.assertions(1);
return expect(promiseHttpsGet(null)).rejects.toThrow(Error);
});
Or the async/await version:
test("Throws on error", async () => {
expect.assertions(1);
await expect(promiseHttpsGet(null)).rejects.toThrow(Error);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With