1import { parse, print } from '@0no-co/graphql.web';
2import { vi, expect, it, beforeEach, MockInstance } from 'vitest';
3
4import { gql } from './gql';
5import { keyDocument } from './utils';
6
7let warn: MockInstance;
8
9beforeEach(() => {
10 warn = vi.spyOn(console, 'warn');
11 warn.mockClear();
12});
13
14it('parses GraphQL Documents', () => {
15 const doc = gql`
16 {
17 gql
18 testing
19 }
20 `;
21
22 expect(doc.definitions).toEqual(
23 parse('{ gql testing }', { noLocation: true }).definitions
24 );
25
26 expect(doc).toBe(keyDocument('{\n gql\n testing\n}'));
27 expect(doc.loc).toEqual({
28 start: 0,
29 end: 19,
30 source: expect.anything(),
31 });
32});
33
34it('deduplicates fragments', () => {
35 const frag = gql`
36 fragment Test on Test {
37 testField
38 }
39 `;
40
41 const doc = gql`
42 query {
43 ...Test
44 }
45
46 ${frag}
47 ${frag}
48 `;
49
50 expect(doc.definitions.length).toBe(2);
51 expect(warn).not.toHaveBeenCalled();
52});
53
54it('warns on duplicate fragment names with different sources', () => {
55 const frag = gql`
56 fragment Test on Test {
57 testField
58 }
59 `;
60
61 const duplicate = gql`
62 fragment Test on Test {
63 otherField
64 }
65 `;
66
67 const doc = gql`
68 query {
69 ...Test
70 }
71
72 ${frag}
73 ${duplicate}
74 `;
75
76 expect(warn).toHaveBeenCalledTimes(1);
77 expect(doc.definitions.length).toBe(2);
78});
79
80it('interpolates nested GraphQL Documents', () => {
81 expect(
82 print(gql`
83 query {
84 ...Query
85 }
86
87 ${gql`
88 fragment Query on Query {
89 field
90 }
91 `}
92 `)
93 ).toMatchInlineSnapshot(`
94 "{
95 ...Query
96 }
97
98 fragment Query on Query {
99 field
100 }"
101 `);
102});
103
104it('interpolates strings', () => {
105 expect(
106 print(
107 gql`
108 query {
109 ${'field'}
110 }
111 `
112 )
113 ).toMatchInlineSnapshot(`
114 "{
115 field
116 }"
117 `);
118});