Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest test .toBeInstanceOf(Error) fails

Tags:

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.

like image 951
PeterDanis Avatar asked Sep 05 '17 10:09

PeterDanis


People also ask

What type of error is thrown if the test fails?

In this case, the test will fail because the WebDriver could not find the element. In this case, StaleElementReferenceException will be thrown.

What is Tohavebeencalled in Jest?

Jest function toHaveBeenCalledWith to ignore object order. 3. Jest to match every object in array.

How do you match objects in Jest?

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' }) ); });


1 Answers

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);
  });
like image 130
PeterDanis Avatar answered Oct 13 '22 18:10

PeterDanis