summaryrefslogtreecommitdiff
path: root/spec/frontend/lib/apollo/persist_link_spec.js
blob: ddb861bcee0b17a59216a669cc2c912be8dea6d1 (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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/* eslint-disable no-underscore-dangle */
import { gql, execute, ApolloLink, Observable } from '@apollo/client/core';
import { testApolloLink } from 'helpers/test_apollo_link';
import { getPersistLink } from '~/lib/apollo/persist_link';

const DEFAULT_QUERY = gql`
  query {
    foo {
      bar
    }
  }
`;

const QUERY_WITH_DIRECTIVE = gql`
  query {
    foo @persist {
      bar
    }
  }
`;

const QUERY_WITH_PERSIST_FIELD = gql`
  query {
    foo @persist {
      bar
      __persist
    }
  }
`;

const terminatingLink = new ApolloLink(() => Observable.of({ data: { foo: { bar: 1 } } }));

describe('~/lib/apollo/persist_link', () => {
  let subscription;

  afterEach(() => {
    if (subscription) {
      subscription.unsubscribe();
    }
  });

  it('removes `@persist` directive from the operation', async () => {
    const operation = await testApolloLink(getPersistLink(), {}, QUERY_WITH_DIRECTIVE);
    const { selections } = operation.query.definitions[0].selectionSet;

    expect(selections[0].directives).toEqual([]);
  });

  it('removes `__persist` fields from the operation with `@persist` directive', async () => {
    const operation = await testApolloLink(getPersistLink(), {}, QUERY_WITH_PERSIST_FIELD);

    const { selections } = operation.query.definitions[0].selectionSet;
    const childFields = selections[0].selectionSet.selections;

    expect(childFields).toHaveLength(1);
    expect(childFields.some((field) => field.name.value === '__persist')).toBe(false);
  });

  it('decorates the response with `__persist: true` is there is `__persist` field in the query', async () => {
    const link = getPersistLink().concat(terminatingLink);

    subscription = execute(link, { query: QUERY_WITH_PERSIST_FIELD }).subscribe(({ data }) => {
      expect(data.foo.__persist).toBe(true);
    });
  });

  it('does not decorate the response with `__persist: true` is there if query is not persistent', async () => {
    const link = getPersistLink().concat(terminatingLink);

    subscription = execute(link, { query: DEFAULT_QUERY }).subscribe(({ data }) => {
      expect(data.foo.__persist).toBe(undefined);
    });
  });
});