summaryrefslogtreecommitdiff
path: root/spec/frontend/__helpers__/test_apollo_link.js
blob: eab0c2de21289cf4857fc3da72d831b59c23ad3c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import { InMemoryCache, ApolloClient, ApolloLink, gql } from '@apollo/client/core';

const FOO_QUERY = gql`
  query {
    foo
  }
`;

/**
 * This function returns a promise that resolves to the final operation after
 * running an ApolloClient query with the given ApolloLink
 *
 * @typedef {Object} TestApolloLinkOptions
 * @property {Object} context the default context object sent along the ApolloLink chain
 *
 * @param {ApolloLink} subjectLink the ApolloLink which is under test
 * @param {TestApolloLinkOptions} options contains options to send a long with the query
 *
 * @returns Promise resolving to the resulting operation after running the subjectLink
 */
export const testApolloLink = (subjectLink, options = {}) =>
  new Promise((resolve) => {
    const { context = {} } = options;

    // Use the terminating link to capture the final operation and resolve with this.
    const terminatingLink = new ApolloLink((operation) => {
      resolve(operation);

      return null;
    });

    const client = new ApolloClient({
      link: ApolloLink.from([subjectLink, terminatingLink]),
      // cache is a required option
      cache: new InMemoryCache(),
    });

    // Trigger a query so the ApolloLink chain will be executed.
    client.query({
      context,
      query: FOO_QUERY,
    });
  });