Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock several gets in fetch-mock?

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?

like image 256
justHelloWorld Avatar asked Feb 28 '18 13:02

justHelloWorld


People also ask

How do you mock fetch in jest?

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.

How does fetch-mock work?

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.

How do you mock a function?

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.


1 Answers

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 });

    //...
}
like image 110
Hatch Avatar answered Sep 20 '22 15:09

Hatch