Git Product home page Git Product logo

react-apollo-async-testing's Introduction

react-apollo-async-testing

Beta: A lightweight way to test your Mutation and Query components in React Apollo (react-apollo).

Install & Usage

On the command line:

npm install --save-dev react-apollo-async-testing

The following test examples showcase this library by using Jest as assertion and test runner library and Enzyme for the actual component renderings and utilities. But Enzyme can be replaced by react-test-renderer as well.

API:

// creates a Apollo Client with sensible defaults (e.g. apollo-cache-inmemory, apollo-http-link)
// just an optional function, you can create your own Apollo Client instance too
// afterward, client instance can be used in the ApolloProvider
const client = createApolloClient('https://api.github.com/graphql');

// enables GraphQL API mocking
// define the GraphQL endpoint URI
// specify a payload object which has a query (and optional variables and operation name)
// specify a result which you would expect from this query
const promise = stubQueryWith(uri, payload, result);

// injects a spied function into the Mutation(s) component(s)
// check sinon library API to interact with the spy
const sinonSpy = injectSpyInMutation();

Query Testing:

The desired goal is to keep you in control of what data should be returned for which request. In addition, you need to be in charge to mimic the different stages of the request by having control over a promise (e.g. pending request, resolved request).

In your application:

import React from 'react';
import gql from 'graphql-tag';
import { Query } from 'react-apollo';

import Repository from './Repository';

export const GET_REPOSITORIES_OF_VIEWER = gql`
  {
    viewer {
      name
      repositories(last: 25) {
        edges {
          node {
            id
            name
            url
            viewerSubscription
          }
        }
      }
    }
  }
`;

const App = () => (
  <Query query={GET_REPOSITORIES_OF_VIEWER}>
    {({ data, loading, error }) => {
      const { viewer } = data;

      if (loading) {
        return <div data-test-id="loading">Loading ...</div>;
      }

      if (error) {
        return <div data-test-id="error">Error ...</div>;
      }

      if (!viewer) {
        return <div data-test-id="no-data">No data ...</div>;
      }

      return (
        <div>
          <div data-test-id="profile">{viewer.name}</div>
          <ul>
            {viewer.repositories.edges.map(({ node }) => (
              <li key={node.id}>
                <Repository repository={node} />
              </li>
            ))}
          </ul>
        </div>
      );
    }}
  </Query>
);

export default App;

In your test:

import React from 'react';
import ReactDOM from 'react-dom';
import { ApolloProvider } from 'react-apollo';

import { mount } from 'enzyme';
import {
  createApolloClient,
  stubQueryWith,
} from 'react-apollo-async-testing';

import App, { GET_REPOSITORIES_OF_VIEWER } from './App';

let client;
let promise;

const viewerWithRepositories = {
  viewer: {
    name: 'Robin Wieruch',
    repositories: {
      edges: [
        {
          node: {
            id: '1',
            name: 'bar',
            url: 'https://bar.com',
            viewerSubscription: 'UNSUBSCRIBED',
          },
        },
        {
          node: {
            id: '2',
            name: 'qwe',
            url: 'https://qwe.com',
            viewerSubscription: 'UNSUBSCRIBED',
          },
        },
      ],
    },
  },
};

beforeAll(() => {
  promise = stubQueryWith(
    'https://api.github.com/graphql',
    {
      query: GET_REPOSITORIES_OF_VIEWER,
    },
    viewerWithRepositories,
  );

  client = createApolloClient('https://api.github.com/graphql');
});

afterAll(() => {
  // since the fetch API is stubbed with the library
  // it has to be restored after the tests
  fetch.restore();
});

test('query result of Query component', done => {
  const wrapper = mount(
    <ApolloProvider client={client}>
      <App />
    </ApolloProvider>,
  );

  expect(wrapper.find('[data-test-id="loading"]')).toHaveLength(1);

  promise.then().then(() => {
    setImmediate(() => {
      wrapper.update();

      expect(wrapper.find('[data-test-id="profile"]')).toHaveLength(
        1,
      );
      expect(wrapper.find('[data-test-id="profile"]').text()).toEqual(
        viewerWithRepositories.viewer.name,
      );

      done();
    });
  });
});

Mutation Testing:

The desired goal is to have a spied function which is used within the Mutation component's children as a function to execute the actual mutation. Only then it is possible to make assertions for the executed mutation.

In your application:

import React from 'react';
import gql from 'graphql-tag';
import { Mutation } from 'react-apollo';

export const WATCH_REPOSITORY = gql`
  mutation($id: ID!, $viewerSubscription: SubscriptionState!) {
    updateSubscription(
      input: { state: $viewerSubscription, subscribableId: $id }
    ) {
      subscribable {
        id
        viewerSubscription
      }
    }
  }
`;

const VIEWER_SUBSCRIPTIONS = {
  SUBSCRIBED: 'SUBSCRIBED',
  UNSUBSCRIBED: 'UNSUBSCRIBED',
};

const isWatch = viewerSubscription =>
  viewerSubscription === VIEWER_SUBSCRIPTIONS.SUBSCRIBED;

const Repository = ({
  repository: { id, url, name, viewerSubscription },
}) => (
  <div>
    <a href={url}>{name}</a>

    <Mutation
      mutation={WATCH_REPOSITORY}
      variables={{
        id,
        viewerSubscription: isWatch(viewerSubscription)
          ? VIEWER_SUBSCRIPTIONS.UNSUBSCRIBED
          : VIEWER_SUBSCRIPTIONS.SUBSCRIBED,
      }}
    >
      {updateSubscription => (
        <button type="button" onClick={updateSubscription}>
          {isWatch(viewerSubscription) ? 'Unwatch' : 'Watch'}
        </button>
      )}
    </Mutation>
  </div>
);

export default Repository;

In your test:

import React from 'react';
import ReactDOM from 'react-dom';
import { ApolloProvider } from 'react-apollo';

import { mount } from 'enzyme';
import {
  createApolloClient,
  injectSpyInMutation,
} from 'react-apollo-async-testing';

import Repository, { WATCH_REPOSITORY, isWatch } from './Repository';

let client;
let sinonSpy;

beforeAll(() => {
  sinonSpy = injectSpyInMutation();

  client = createApolloClient('https://api.github.com/graphql');
});

test('interaction with mutation function from the Mutation component', () => {
  const repository = {
    id: '1',
    name: 'foo',
    url: 'https://foo.com',
    viewerSubscription: 'UNSUBSCRIBED',
  };

  const wrapper = mount(
    <ApolloProvider client={client}>
      <Repository repository={repository} />
    </ApolloProvider>,
  );

  wrapper.find('button').simulate('click');

  expect(sinonSpy.calledOnce).toEqual(true);

  const expectedObject = {
    mutation: WATCH_REPOSITORY,
    variables: {
      id: repository.id,
      viewerSubscription: 'SUBSCRIBED',
    },
  };

  expect(sinonSpy.calledWith(expectedObject)).toEqual(true);
});

Example

A simple example application which uses tested Mutation and Query components can be found in the example/ folder.

Install:

  • git clone [email protected]:rwieruch/react-apollo-async-testing.git
  • cd react-apollo-async-testing/example
  • npm install

Run tests:

  • npm test

Run application:

react-apollo-async-testing's People

Contributors

rwieruch avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

Forkers

oyes704 thmnshmv

react-apollo-async-testing's Issues

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didn’t receive a CI status on the greenkeeper/initial branch, it’s possible that you don’t have CI set up yet. We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please delete the greenkeeper/initial branch in this repository, and then remove and re-add this repository to the Greenkeeper App’s white list on Github. You'll find this list on your repo or organization’s settings page, under Installed GitHub Apps.

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didn’t receive a CI status on the greenkeeper/initial branch, it’s possible that you don’t have CI set up yet. We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please delete the greenkeeper/initial branch in this repository, and then remove and re-add this repository to the Greenkeeper App’s white list on Github. You'll find this list on your repo or organization’s settings page, under Installed GitHub Apps.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.