How to make Jest wait for all asynchronous code to finish execution before expecting an assertion

Updated for Jest 27+ For jest 27+, you can also use process.nextTick: await new Promise(process.nextTick); (Thanks to Adrian Godong in the comments) Original Answer Here’s a snippet that waits until pending Promises are resolved: const flushPromises = () => new Promise(setImmediate); Note that setImmediate is a non-standard feature (and is not expected to become standard). … Read more

Jest mock inner function

If an ES6 module directly exports two functions (not within a class, object, etc., just directly exports the functions like in the question) and one directly calls the other, then that call cannot be mocked. In this case, funcB cannot be mocked within funcA the way the code is currently written. A mock replaces the … Read more

How do I test axios in Jest?

Without using any other libraries: import * as axios from “axios”; // Mock out all top level functions, such as get, put, delete and post: jest.mock(“axios”); // … test(“good response”, () => { axios.get.mockImplementation(() => Promise.resolve({ data: {…} })); // … }); test(“bad response”, () => { axios.get.mockImplementation(() => Promise.reject({ … })); // … }); … Read more