0

Is it possible to test that a code path is not executed in a test case in Jest? For example, in the following test, I want the then part to execute (which has an expect but I don't want the catch part to execute. Will jest automatically fail the test if catch part is hit and it can't find an expect in it?

describe("Endpoints are accessible", () => {
    it("GET request for homepage should return 200", async () => {
      const baseURL = process.env.EXPRESS_SERVER_TEST 
      console.log(`base url is ${baseURL}`);
      
      const req = {};
      
      const res = {};
      
      indexControllerModule.homepageHandler(req,res)
      .then((result)=>{
        console.log(`result is ${result}`);
        expect(result).toBe(JSON.stringify({
          "message": "welcome"
        }));
      })
      .catch((error)=>{
        console.log(`This code path shouldn't be executed. Error in accessing homepage: ${error}`);
      })
    });  
});
Manu Chadha
  • 15,555
  • 19
  • 91
  • 184

1 Answers1

0

Just remove .catch.

Assuming your timeout is long enough the promise will either resolve (.then) or reject (.catch). If rejected the promise will throw an error which is treated as a failed test by jest. But by catching the rejected promise you prevent the test from failing.

Hoopra
  • 201
  • 2
  • 7
  • Thanks. Would it work the other way as well. i.e. the test should fail so I should have a `catch`, not `then`? – Manu Chadha Sep 01 '23 at 16:50
  • in that case you can use jest `await expect(functionCall()).rejects.toThrow()`. https://stackoverflow.com/questions/47144187/can-you-write-async-tests-that-expect-tothrow – Hoopra Sep 01 '23 at 18:50