Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if a void async function was successful with jest?

How do you concisely test if a void async function executed successfully with jest? I'm using TypeScript.

// foo.ts
export class Foo {
  public async bar(): Promise<void> {
    await someAsync();
  }
}

How to test that new Foo().bar() does not throw an error?

like image 460
adanilev Avatar asked Mar 19 '19 02:03

adanilev


People also ask

How do you test asynchronous code in Jest?

There is an alternate form of test that fixes this. Instead of putting the test in a function with an empty argument, use a single argument called done . Jest will wait until the done callback is called before finishing the test.

Which of the following methods are used to test an asynchronous code by using Jest?

Testing With Async / Await As we saw in the previous section, Jest will know that we are dealing with asynchronous code if we return a Promise object form the test function. If we declare the test function as async , it will implicitly make the function to return a Promise.

How do you test Promise reject Jest?

Try-catch with async/await (bad) It looks like using try-catch with async/await is the easiest way to achieve this as the rejected value is thrown: it("rejects (bad)", async () => { try { await promiseMe("Error"); } catch (e) { expect(e). toEqual("Error"); } }); But wait.

How do you mock a Promise response in Jest?

In order to mock asynchronous code in Jest, more specifically Promises, you can use the mockResolvedValue function. This will mock the return value of the Promise to be 42. In order to test a Promise in Jest, you need to turn your it block into async in order to use the await keyword in front of an expect statement.


2 Answers

This is the most semantic way I've found. It is even just a translation of the test name.

describe("Foo.bar()", () => {
      test("Should not throw", async () => {
        await expect(new Foo().bar()).resolves.not.toThrow();
      });
    });
like image 135
Mr Menezes Avatar answered Sep 22 '22 17:09

Mr Menezes


The Promise has the advantage that it should not throw at all, rather be resolved or rejected. On the other hand the toBe() assertion expects an argument, even though there is a Promise<void> in TypeScript.

So what if there is no argument passed (or the argument is void) but it is still evaluated. The the argument is undefined.

  test("Should resolve", async () => {
      await expect(new Foo().bar()).resolves.toBe(undefined);
  });

Testing for not.toThrow() happend to be a false friend for me, because my Foo.bar() did not throw, nor was it resolved either.

like image 37
Alex Avatar answered Sep 25 '22 17:09

Alex