从服务器端测试graphql api时,Apollo客户端ECONNREFUSED

时间:2018-09-06 11:15:00

标签: node.js apollo-client apollo-server

这就是我测试我的graphql api的方式。我正在使用Mocha进行测试,在测试开始时,我先启动apollo serverinitialize database,然后扫描要添加到mocha的测试文件,然后运行它。之后,我关闭服务器和数据库。

为了更好地理解这一点,以下是详细信息

// folder structure - graphql-server
// there are src/, config/ and other stuff but only show tests directory tree
.
..
tests/
  unit_tests/
    mutation/
      user.test.js
    query/
      hello.test.js
    index.test.js // where tests are setup
  utils/
    apolloClient.js // The Apollo Client
    scanTestsAt.js // get path to test files to add to mocha
    testConfig.js  // just some config like graphql endpoint, server port, etc

测试设置代码

// index.test.js
import ...

describe('Unit tests', function() {
  const mocha = new Mocha({ useColors: true, fullStackTrace: true });
  let server = null;

  before(function () {
    return new Promise(function(resolve) {
      db
        .sequelize
        .sync({ force: true, match: /_test$/ })
        .then(function () {
          server = app.listen({ port: config.testServerPort }, function () {
            resolve();
          });
        });
    });
  });

  ['mutation', 'query'].forEach(function(dirName) {
    scanTestAt(`tests/unit_tests/${dirName}`, mocha);
  });

  it('=======UnitTesting=======', function() {
    mocha.run();
  });

  after(function() {
    db.sequelize.close();
    server.close();
  });
});

阿波罗客户代码

// tests/utils/apolloClient.js

import { ApolloClient } from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import fetch from 'node-fetch';

import config from './testConfig';

const link = new HttpLink({
  uri: `http://localhost:${config.testServerPort}/${config.graphqlEndpoint}`,
  fetch
});

const cache = new InMemoryCache();

const client = new ApolloClient({ link, cache });

export default client;

一个非常简单的查询代码,可确保我们设置基本权限

// tests/unit_tests/query/hello.test.js

import { expect, should } from 'chai';
import { describe, it } from 'mocha';
import { gql } from 'apollo-server-express';

import client from '../../utils/apolloClient';

describe('hello query', function() {
  it('should return Hello World to ensure graphql server is working at the basic', async function() {
    const query = gql`{ hello }`;

    const { data } = await client.query({ query });

    expect(data.hello).to.equal('Hello World');
  });
});

错误:

// NOTE: I used '~' to hide the path here, but it is actually full path

Error: Network error: request to http://localhost:3000/graphql failed, reason: connect ECONNREFUSED 127.0.0.1:3000
  at new ApolloError (~/projects/connect-apollo-postgres-boilerplate/node_modules/src/errors/ApolloError.ts:56:5)
  at Object.error (~/projects/connect-apollo-postgres-boilerplate/node_modules/src/core/QueryManager.ts:300:13)
  at notifySubscription (~/projects/connect-apollo-postgres-boilerplate/node_modules/zen-observable/lib/Observable.js:130:18)
  at onNotify (~/projects/connect-apollo-postgres-boilerplate/node_modules/zen-observable/lib/Observable.js:161:3)
  at SubscriptionObserver.error (~/projects/connect-apollo-postgres-boilerplate/node_modules/zen-observable/lib/Observable.js:220:7)
  at ~/projects/connect-apollo-postgres-boilerplate/node_modules/apollo-link-http/src/httpLink.ts:163:20
  at process._tickCallback (internal/process/next_tick.js:68:7)

但是,当我在外部运行服务器时,注释掉前后代码并在另一个终端上运行测试,所有测试都将成功运行。

如果我改为在相同的index.test.js内运行测试,它也会成功运行,如下所示:

// index.test.js

...
before(function() { ...same codes });

// ...everything same
// except this
it('=======UnitTesting=======', function() {
  // mocha.run(); comment this out and copy all the codes from hello.test.js and user.test.js (contains basic signup and login test)

  // copy paste codes...
  // all test run successfully
});


after(function() { ...same codes });

因此,如何解决阿波罗客户端拒绝连接到http://localhost:3000/graphql的错误

编辑1:这就是我运行测试的方式

// package.json

...
"scripts": {
  ...
  "unit-test": "NODE_ENV=test NODE_PATH=./ mocha --recursive --require @babel/register -- tests/unit_tests/index.test.js"
},
...

// outside on the terminal, at the server root directory
npm run unit-test

编辑2:我现在仅使用graphql来测试我的resolverssubscriptions,而不是使用Apollo Client,因此对我来说这个问题已经解决了。

0 个答案:

没有答案