I'm writing unit tests to check my api. Before I merged my git
test branch with my dev branch everything was fine, but then I started to get this error:
App running at: http://localhost:4096/
spacejam: meteor is ready
spacejam: spawning phantomjs
phantomjs: Running tests at http://localhost:4096/local using test-in-console
phantomjs: Error: fetch is not found globally and no fetcher passed, to fix pass a fetch for
your environment like https://www.npmjs.com/package/unfetch.
For example:
import fetch from 'unfetch';
import { createHttpLink } from 'apollo-link-http';
const link = createHttpLink({ uri: '/graphql', fetch: fetch });
Here's a part of my api.test.js
file:
describe('GraphQL API for users', () => {
before(() => {
StubCollections.add([Meteor.users]);
StubCollections.stub();
});
after(() => {
StubCollections.restore();
});
it('should do the work', () => {
const x = 'hello';
expect(x).to.be.a('string');
});
});
The funniest thing is that I don't even have graphql
in my tests (although, I use it in my meteor
package)
Unfortunately, I didn't to find enough information (apart from apollo-link-http docs that has examples, but still puzzles me). I did try to use that example, but it didn't help and I still get the same error
If you're using nodejs do the following:
Install
node-fetch
Add the line below to
index.js
:The problem is this:
fetch
is defined when you are in the browser, and is available asfetch
, or evenwindow.fetch
In the server it is not defined, and either needs to be imported explicity, or a polyfill like https://www.npmjs.com/package/unfetch (as suggested in the error message) needs to be imported by your test code to make the problem go away.
I got the same error importing a npm module doing graphql queries into my React application. The app was compiling but tests were failing since
window.fetch
is not available in the Node.js runtime.I solved the problem by installing
node-fetch
https://www.npmjs.com/package/node-fetch and adding the following declarations tojest.config.js
:Doing so we instruct Jest on how to handle
window.fetch
when it executes frontend code in the Node.js runtime.