{"id":645,"hash":"e566e7f65b0300800d25641a11e961e0d0327b50b9e1972538746cde80fd961c","pattern":"How to test the type of a thrown exception in Jest","full_message":"I'm working with some code where I need to test the type of an exception thrown by a function (is it TypeError, ReferenceError, etc.?).\n\nMy current testing framework is AVA and I can test it as a second argument t.throws method, like here:\n\nit('should throw Error with message \\'UNKNOWN ERROR\\' when no params were passed', (t) => {\n  const error = t.throws(() => {\n    throwError();\n  }, TypeError);\n\n  t.is(error.message, 'UNKNOWN ERROR');\n});\n\nI started rewriting my tests in Jest and couldn't find how to easily do that. Is it even possible?","ecosystem":"npm","package_name":"unit-testing","package_version":null,"solution":"In Jest you have to pass a function into expect(function).toThrow(<blank or type of error>).\n\nExample:\n\ntest(\"Test description\", () => {\n  const t = () => {\n    throw new TypeError();\n  };\n  expect(t).toThrow(TypeError);\n});\n\nOr if you also want to check for error message:\n\ntest(\"Test description\", () => {\n  const t = () => {\n    throw new TypeError(\"UNKNOWN ERROR\");\n  };\n  expect(t).toThrow(TypeError);\n  expect(t).toThrow(\"UNKNOWN ERROR\");\n});\n\nIf you need to test an existing function whether it throws with a set of arguments, you have to wrap it inside an anonymous function in expect().\n\nExample:\n\ntest(\"Test description\", () => {\n  expect(() => {http.get(yourUrl, yourCallbackFn)}).toThrow(TypeError);\n});","confidence":0.95,"source":"stackoverflow","source_url":"https://stackoverflow.com/questions/46042613/how-to-test-the-type-of-a-thrown-exception-in-jest","votes":593,"created_at":"2026-04-19T04:51:27.254105+00:00","updated_at":"2026-04-19T04:51:27.254105+00:00"}