在流星中使用spacejam时,"在全局范围内找不到提取而没有提取器"

Le *_*con 9 javascript testing meteor graphql

我正在编写单元测试来检查我的api.在我将我的git 测试分支与我的dev分支合并之前,一切都很好,但后来我开始收到此错误:

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 });
Run Code Online (Sandbox Code Playgroud)

这是我api.test.js文件的一部分:

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');
    });
  });
Run Code Online (Sandbox Code Playgroud)

最有趣的是我甚至没有graphql在我的测试中(虽然,我在我的meteor包中使用它)不幸的是,我没有找到足够的信息(除了apollo-link-http文档有示例,但仍然困惑我).我确实尝试使用该示例,但它没有帮助,我仍然得到相同的错误

Bra*_*rad 7

如果您使用的是 nodejs,请执行以下操作:

安装 node-fetch

npm install --save node-fetch
Run Code Online (Sandbox Code Playgroud)

将下面的行添加到index.js

global.fetch = require('node-fetch');
Run Code Online (Sandbox Code Playgroud)


Ray*_*Mik 5

导入一个执行graphql查询的npm模块到我的React应用程序中,我遇到了同样的错误。该应用程序正在编译,但是测试失败,因为window.fetchNode.js运行时中不可用。

我通过安装node-fetch https://www.npmjs.com/package/node-fetch并将以下声明添加到来解决了该问题jest.config.js

const fetch = require('node-fetch')

global.fetch = fetch
global.window = global
global.Headers = fetch.Headers
global.Request = fetch.Request
global.Response = fetch.Response
global.location = { hostname: '' }
Run Code Online (Sandbox Code Playgroud)

这样做是为了指导Jest在window.fetchNode.js运行时中如何执行前端代码。


Mik*_*kel 4

问题是这样的:fetch当您在浏览器中时定义,并且可以作为fetch,甚至window.fetch

在服务器中它没有定义,要么需要显式导入,要么需要由测试代码导入像https://www.npmjs.com/package/unfetch (如错误消息中所建议的)这样的polyfill让问题消失。