If you have a service or module that you need to mock for tests, you can easily do this with Jest.
In order to mock one of your own services, to set it up, you can do the following in your test file:
import serviceToBeMocked from "./path/to/service";
...
jest.mock("./path/to/service", () => ({
functionToBeMocked: jest.fn()
}));
From there, you can mock the implementation where you need it, for example:
describe("renders", () => {
...
serviceToBeMocked.functionToBeMocked.mockImplementation(() => {
return yourMockData;
})
...
});
If you need to mock a module used in your application, you can also use Jest for this. If you needed to mock Axios for example, you can do the following:
...
import axios from "axios";
jest.mock("axios");
axios.mockImplementationOnce(() =>
Promise.resolve({
data: {
id: 1,
name: "Joe Soap",
...
}
})
);
...
When it comes time to make your assertions, can do the following:
it("does something", async () => {
...
await wait(() => {
expect(axios).toHaveBeenCalledTimes(1);
});
...
});