I have a method to get product data from an API. I use Axios to call the API. Since the product data is independent of each other, I call all the APIs at once and use Promise.all to wait for the calls to complete before proceeding. For example, consider a function (not enclosed in a function statement) with below lines.
const productIds = [ "SKU-1", "SKU-2" ];
const promises = productIds.map<Promise<Product>>(id => axios.get(`/products/${id}`));
Promise.all(promises).then(values => {
// do some stuff here.
});
The unit test case written uses jest mock implementation as below.
import http from "axios";
import { sku1, sku2 } from "./test-product-data";
jest.mock("axios", () => ({
create: jest.fn(() => http),
get: jest.fn(() => Promise.resolve()),
}));
const httpMock = http as jest.Mocked<typeof http>;
describe("Update operations!", () => {
beforeAll(() => {
httpMock.get.mockImplementation(url => {
// Call to Get product.
if (url.endsWith("/SKU-1")) {
mockedSuccessResponse.data = Object.assign({}, sku1);
return Promise.resolve(mockedSuccessResponse);
};
if (url.endsWith("/SKU-2")) {
mockedSuccessResponse.data = Object.assign({}, sku2);
return Promise.resolve(mockedSuccessResponse);
};
});
});
});
Jest returns the response of the last API call, i.e. the response of SKU-2 even for the product with id SKU-1. Am I missing something?