3
votes

I am working on mocking graphql api in my react app using apollo client. This is my index.js (react app created by create-react-app)

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import InventoryList from './components/InventoryList';
import Header from './components/Header';
import Footer from './components/Footer';
import Settings from './components/Settings';
import registerServiceWorker from './registerServiceWorker';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import { ApolloClient } from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { ApolloProvider } from 'react-apollo';
import { mockNetworkInterfaceWithSchema } from 'apollo-test-utils';
import {typeDefs} from './components/schema';
import { makeExecutableSchema, addMockFunctionsToSchema } from 'graphql-tools';

const schema = makeExecutableSchema({ typeDefs });
addMockFunctionsToSchema({ schema });

const mockNetworkInterface = mockNetworkInterfaceWithSchema({ schema });

const client = new ApolloClient({
  // By default, this client will send queries to the
  //  `/graphql` endpoint on the same host
  // Pass the configuration option { uri: YOUR_GRAPHQL_API_URL } to the `HttpLink` to connect 
  // to a different host

  link: new HttpLink({ uri: 'http://localhost:3000/graphql'}),
  networkInterface: mockNetworkInterface,
  cache: new InMemoryCache(),
});

// Requesting data
client.query({ query: gql`{ hello }` }).then(console.log);

ReactDOM.render(
  <ApolloProvider client={client}>
    <Router>
      <div>
        <Header />
        <Route exact path="/" component={App} />
        <Route exact path="/inventory" component={InventoryList} />
        <Route exact path="/settings" component={Settings} />
        <Footer />
      </div>
    </Router>
  </ApolloProvider>,
  document.getElementById('root')
)
registerServiceWorker();

This is my component LoggedInUser (child of app component)-

import React from 'react';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
import {typeDefs} from './schema';
import { makeExecutableSchema, addMockFunctionsToSchema } from 'graphql-tools';

const schema = makeExecutableSchema({ typeDefs });
addMockFunctionsToSchema({ schema });

const usersListQuery = gql`
  query UsersListQuery {
    users {
      id
      name
    }
  }
`;

function LoggedInUsers({ data: { users, refetch, loading, error } }) {
  return (
    <div>
      {/*<button onClick={() => refetch()}>
        Refresh
      </button> */}
      <ul>
        {users && users.map(user => (
          <li key={user.id}>
            {user.name}
          </li>
        ))}
      </ul>
    </div>
  );
}

export default graphql(usersListQuery)(LoggedInUsers);

I am just confused how to hit mock API as currently I am getting console error: POST http://localhost:3000/graphql 404 (Not Found)

I was following this tutorial - https://dev-blog.apollodata.com/full-stack-react-graphql-tutorial-582ac8d24e3b

1

1 Answers

1
votes

This definition seems odd to me. In particular the definition of link and networkInterface next to each other in the Apollo Client options.

const client = new ApolloClient({
  link: new HttpLink({ uri: 'http://localhost:3000/graphql'}),
  networkInterface: mockNetworkInterface,
  cache: new InMemoryCache(),
});

The interface for Apollo has changed recently. In Apollo Client > 2.0 the client takes a single link. A link is an adapter that accepts queries and returns results. Before 2.0 the client would use a network interface which was a similar concept but would imply that a network request is executed. Links on the other hand don't have to make network requests or pretend to. Furthermore they can be composed more easily and many different links have already been developed. It seems like you are using Apollo Client in a version greater than 2.0. The project apollo-test-utils seems to be mostly abandoned. It seems to be replaced by apollo-link-schema. The mocking section describes how to use the link to mock data.