1
votes

I am writing a jest test that expects an error to be thrown:

it("safeGithubPush()", () => {
  const err = new Error('job not valid')
  expect(productionDeployJob.safeGithubProdPush(unsafeJob)).toThrow(err);
});

The error is thrown. However, rather than jest passing this test, it says it fails and points to where this error is created in my program

FAIL  tests/unit/productionDeploy.test.js
● ProductionDeploy Test Class › safeGithubPush()

job not valid

   8 | const uploadToS3Timeout = 20;
   9 | 
> 10 | const invalidJobDef = new Error("job not valid");

Why does it complain that the error was thrown when I tell it to expect this same error?

1

1 Answers

2
votes

You are calling the safeGithubProdPush method in-place.

In order for Jest to catch the error thrown by the method you should give expect a function wrapping the call:

expect(() => productionDeployJob.safeGithubProdPush(unsafeJob)).toThrow(err);

As in the docs:

Note: You must wrap the code in a function, otherwise the error will not be caught and the assertion will fail.

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