I'll-Be-Back
I'll-Be-Back

Reputation: 10828

Jest - expect throw message test

I am trying to write a test to test if an error has thrown

exports.handler = async data => {
  try {
      throw new Error("Invalid Data")
    };
  } catch (err) {
    throw err;
  }
};

I wrote a test which is working as expected

it("Throw Error Invalid Data", async () => {
    try {
       await function.handler({});
    } catch (err) {
      expect(err).toEqual(new Error("Invalid Data"));
    }
})

How do avoid using try/catch block in the test?

Upvotes: 2

Views: 1565

Answers (2)

nem035
nem035

Reputation: 35481

You can use the .rejects helper:

it("Throw Error Invalid Data", () => {
  return expect(handler({})).rejects.toEqual(new Error("Invalid Data"));
});

Or with an async function:

it("Throw Error Invalid Data", async () => {
  await expect(handler({})).rejects.toEqual(new Error("Invalid Data"));
});

Upvotes: 2

nicholaswmin
nicholaswmin

Reputation: 22949

Like this:

await expect(handler({})).rejects.toThrow(new Error("Invalid Data"));

Upvotes: 1

Related Questions