I'm testing my react components and I want to mock several get
operations. What I want to do is something like:
test(`Created correctly`, async () => {
fetchMock.get(`*`, JSON.stringify(FIRSTGETOBJ));
fetchMock.get(`*`, JSON.stringify(SECONDGETOBJ));
fetchMock.get(`*`, JSON.stringify(THIRDGETOBJ));
//...
}
The url for each get
is the same, but the payload changes. However, using the code above I will get:
Error: Adding route with same name as existing route. See `overwriteRoutes` option.
How can I do this?
We have to mock both promises with jest. fn to get the same behavior: By doing this, when the function getPricesLastDays calls fetch, the mocked out version of fetch will be called. Thus, we have a predictable return.
fetch-mock allows mocking http requests made using fetch or a library imitating its api, such as node-fetch or fetch-ponyfill. It supports most JavaScript environments, including Node. js, web workers, service workers, and any browser that either supports fetch natively or that can have a fetch polyfill installed.
There are two ways to mock functions: Either by creating a mock function to use in test code, or writing a manual mock to override a module dependency.
Use overwriteRoutes
option
test(`Created correctly`, async () => {
fetchMock.get(`*`, JSON.stringify(FIRSTGETOBJ));
fetchMock.get(`*`, JSON.stringify(SECONDGETOBJ), { overwriteRoutes: false });
fetchMock.get(`*`, JSON.stringify(THIRDGETOBJ), { overwriteRoutes: false });
//...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With