Real Fetching in Jest

Di.rk
2 min readOct 7, 2021

without the mock

Sometimes it makes no sense for me to test against mocked services, because you are creating you own reality in those test that has nothing to do with the real world and data outside.

In those cases I have to replace the browser fetch api through something in NodeJs. It takes me a while to get this done for a VueJs environment using the CLI because it complains about multiple problems I thought somebody still have solved, so I does not have to figure it out.

The first problem was to use async/await in my code. At the moment Jest does not support this automatically and complains with

> vue-cli-service test:unit "data-services.spec"
FAIL src/services/data-services/tests/data-services.spec.js
● Test suite failed to run
ReferenceError: regeneratorRuntime is not defined

Some googling time later i figuered out that I have to add this to my test file:

import 'regenerator-runtime/runtime'

That means you have to install ‘regenerator-runtime/runtime’ in front with

npm install -D regenerator-runtime

Than it went away.

But now what NodeJs fetch API to use.

was not the right choice because it does not fits with the environment, complaining about missing module support in the nested source.

In the end after googling around some time I found the one that does it:

So

npm install -D regenerator-runtime

does the Job simply by

import 'regenerator-runtime/runtime'
import fetch from 'isomorphic-fetch'

This API can be injected into your code implementing the fetch API and it simply works.

Hope I could help someone with this.

--

--