lundi 5 août 2019

Jest: Testing changes in catch block - Why does this work

Using Jest, I want to reject a promise and check that the result of the code in my catch block.

I have got it working, but I don't really understand why and was hoping someone would be able to explain it to me.

Here is a very simple example of my test that fails

let check = "";

const sFunc = () => {
  aFunc()
    .then(resp => check = resp)
    .catch(error =>  check = error)
};

let aFunc = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      return resolve("Resolved");
    }, 1000);
  });
};

it("Resolve test", async () => {
  expect.assertions(1)
  sFunc();
  await aFunc();
  expect(check).toEqual("Resolved");
});

it("Reject Test", async () => {
  aFunc = jest.fn().mockRejectedValue("Rejected");
  expect.assertions(1)
  sFunc();
  await aFunc; // or await aFunc()
  expect(check).toEqual("Rejected"); // Fails - receives "Resolved" or times out with aFunc() 
});

Now if I change the Reject Test to the following it works and I get the expect result

let check = "";
const sFunc = () => {
  aFunc()
    .then(resp => check = resp)
    .catch(error =>  check = error)
};
let aFunc = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      return resolve("Resolved");
    }, 1000);
  });
};

it("Resolve test", async () => {
  expect.assertions(1)
  sFunc();
  await expect(aFunc()).resolves.toEqual("Resolved");
  expect(check).toEqual("Resolved");
});

it("Reject Test", async () => {
  aFunc = jest.fn().mockRejectedValue("Rejected");
  expect.assertions(1)
  sFunc();
  await expect(aFunc()).rejects.toEqual("Rejected");
  expect(check).toEqual("Rejected");
});

Basically, I changed the line to await expect(aFunc()).rejects.toEqual("Rejected");

Could someone please explain why adding the expect causes it to wait for the catch block to be completed please.

Any help would be greatly appreciated

Aucun commentaire:

Enregistrer un commentaire