phpsmarter
1/20/2018 - 2:27 AM

A working example of graphql and apollo client test

A working example of graphql and apollo client test

import 'mocha';
import {expect} from 'chai';

import 'isomorphic-fetch';
import ApolloClient from 'apollo-client';
import gql from 'graphql-tag';
import {print} from 'graphql-tag/bundledPrinter';

describe('some test', () => {
  it('should pass', () => {
    const query = gql`
    query people {
      allPeople(first: 1) {
        people {
          name
        }
      }
    }
  `;

    const result = {
      data: {
        allPeople: {
          people: [
            {
              name: 'Luke Skywalker',
            },
          ],
        },
      },
    };

    const networkInterface = new MockNetworkInterface({
      request: {query},
      result
    });

    const client = new ApolloClient({
      networkInterface,
      addTypename: false
    });

    return client.query({query})
      .then(d => {
        return expect(d.data).to.eql(result.data);
      });
  });
});


class MockNetworkInterface {
  mockedResponsesByKey = [];

  constructor(mockedResponse) {
    this.addMockedResponse(mockedResponse);
  }

  addMockedResponse(mockedResponse) {
    const key = requestToKey(mockedResponse.request);
    let mockedResponses = this.mockedResponsesByKey[key];
    if (!mockedResponses) {
      mockedResponses = [];
      this.mockedResponsesByKey[key] = mockedResponses;
    }
    mockedResponses.push(mockedResponse);
  }

  query(request) {
    return new Promise((resolve, reject) => {
      const parsedRequest = {
        query: request.query,
        variables: request.variables,
        debugName: request.debugName,
      };

      const key = requestToKey(parsedRequest);
      const responses = this.mockedResponsesByKey[key];
      if (!responses || responses.length === 0) {
        throw new Error(`No more mocked responses for the query: ${print(request.query)}, variables: ${JSON.stringify(request.variables)}`);
      }

      const {result, error, delay} = responses.shift();

      if (!result && !error) {
        throw new Error(`Mocked response should contain either result or error: ${key}`);
      }

      setTimeout(() => {
        if (error) {
          reject(error);
        } else {
          resolve(result);
        }
      }, delay ? delay : 0);
    });
  }
}

function requestToKey(request) {
  const queryString = request.query && print(request.query);

  return JSON.stringify({
    variables: request.variables || {},
    debugName: request.debugName,
    query: queryString,
  });
}