graphql-data-generator 0.3.0-alpha.3 → 0.3.0-alpha.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esm/jest.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import * as dntShim from "./_dnt.shims.js";
2
2
  import React, { useMemo } from "react";
3
- import { ApolloLink } from "@apollo/client";
4
- import { ErrorLink } from "@apollo/client/link/error/index.js";
5
- import { MockedProvider, MockLink, } from "@apollo/client/testing/index.js";
3
+ import { ApolloLink, useApolloClient, } from "@apollo/client";
4
+ import { ErrorLink } from "@apollo/client/link/error";
5
+ import { MockedProvider, MockLink, } from "@apollo/client/testing";
6
6
  import { waitFor } from "@testing-library/dom";
7
- import { print } from "graphql";
7
+ import { Kind, print } from "graphql";
8
8
  import { diff as jestDiff } from "jest-diff";
9
9
  let currentSpecResult;
10
10
  jasmine.getEnv().addReporter({
@@ -12,18 +12,11 @@ jasmine.getEnv().addReporter({
12
12
  });
13
13
  const afterTest = [];
14
14
  afterEach(async () => {
15
- for (const hook of afterTest)
15
+ const hooks = afterTest.splice(0);
16
+ for (const hook of hooks)
16
17
  await hook();
17
- afterTest.splice(0);
18
18
  });
19
- const diff = (a, b) => jestDiff(a, b, {
20
- omitAnnotationLines: true,
21
- // aColor: green,
22
- // bColor: red,
23
- // changeColor: inverse,
24
- // commonColor: dim,
25
- // patchColor: yellow,
26
- })
19
+ const diff = (a, b) => jestDiff(a, b, { omitAnnotationLines: true })
27
20
  ?.replace(/\w+ \{/g, "{") // Remove class names
28
21
  .replace(/\w+ \[/g, "["); // Remove array class names
29
22
  const getErrorMessage = (operation, mockLink) => {
@@ -38,7 +31,7 @@ const getErrorMessage = (operation, mockLink) => {
38
31
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
39
32
  const alts = (mockLink
40
33
  .mockedResponsesByKey[key] ?? []);
41
- let errorMessage = `Expected GraphQL ${operationType} ${operation.operationName} to have been mocked`;
34
+ let errorMessage = `Expected ${operationType} ${operation.operationName} to have been mocked`;
42
35
  if (alts.length || Object.keys(operation.variables).length > 0) {
43
36
  errorMessage += ` with variables ${dntShim.Deno.inspect(operation.variables, { depth: Infinity, colors: true })}`;
44
37
  }
@@ -61,13 +54,38 @@ const getErrorMessage = (operation, mockLink) => {
61
54
  : undefined,
62
55
  };
63
56
  };
57
+ let _failRefetchWarnings = false;
58
+ /**
59
+ * In older versions of `@apollo/client`, refetches with missing mocks trigger
60
+ * warnings instead of being treated as standard missing mocks.
61
+ * This utility converts those warnings into failures and ensures watch queries
62
+ * are installed for queries with `watch: true`.
63
+ */
64
+ export const failRefetchWarnings = (value = true) => _failRefetchWarnings = value;
65
+ const AutoWatch = ({ mocks }) => {
66
+ const client = useApolloClient();
67
+ for (const mock of mocks)
68
+ if (mock.watch)
69
+ client.watchQuery(mock.request);
70
+ return null;
71
+ };
64
72
  export const MockProvider = ({ mocks, stack: renderStack, children }) => {
65
73
  const observableMocks = useMemo(() => {
66
- const observableMocks = mocks.map((m) => ({
67
- ...m,
68
- stack: m.stack,
69
- result: Object.assign(jest.fn(() => m.result), m.result),
70
- }));
74
+ const observableMocks = mocks.flatMap((m) => [
75
+ {
76
+ ...m,
77
+ stack: m.stack,
78
+ result: Object.assign(jest.fn(() => m.result), m.result),
79
+ },
80
+ ...(m.watch
81
+ ? [{
82
+ ...m,
83
+ stack: m.stack,
84
+ result: Object.assign(jest.fn(() => m.result), m.result),
85
+ watch: false,
86
+ }]
87
+ : []),
88
+ ]);
71
89
  afterTest.push(async () => {
72
90
  if (currentSpecResult.failedExpectations.length)
73
91
  return;
@@ -78,7 +96,8 @@ export const MockProvider = ({ mocks, stack: renderStack, children }) => {
78
96
  if (currentSpecResult.failedExpectations.length)
79
97
  return;
80
98
  if (mock.result.mock.calls.length === 0) {
81
- const err = new Error(`Expected to have used mock${mock.request.variables
99
+ const operation = mock.request.query.definitions.find((d) => d.kind === Kind.OPERATION_DEFINITION);
100
+ const err = new Error(`Expected to have used ${operation?.operation} ${operation?.name?.value}${mock.request.variables
82
101
  ? ` with variables ${dntShim.Deno.inspect(mock.request.variables, {
83
102
  depth: Infinity,
84
103
  colors: true,
@@ -113,5 +132,30 @@ export const MockProvider = ({ mocks, stack: renderStack, children }) => {
113
132
  // @ts-ignore It's fine
114
133
  return ApolloLink.from([errorLoggingLink, mockLink]);
115
134
  }, [observableMocks, renderStack]);
116
- return React.createElement(MockedProvider, { link: link }, children);
135
+ if (_failRefetchWarnings) {
136
+ const oldWarn = console.warn.bind(console.warn);
137
+ console.warn = (message, operation, ...etc) => {
138
+ if (message !==
139
+ 'Unknown query named "%s" requested in refetchQueries in options.include array') {
140
+ return oldWarn(message, operation, ...etc);
141
+ }
142
+ try {
143
+ fail({
144
+ name: "Error",
145
+ message: `Expected query ${operation} requested in refetchQueries options.include array to have bene mocked`,
146
+ stack: renderStack,
147
+ });
148
+ }
149
+ catch {
150
+ // eat
151
+ }
152
+ };
153
+ afterTest.push(() => {
154
+ console.warn = oldWarn;
155
+ });
156
+ }
157
+ return (React.createElement(MockedProvider, { link: link },
158
+ React.createElement(React.Fragment, null,
159
+ React.createElement(AutoWatch, { mocks: observableMocks }),
160
+ children)));
117
161
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "graphql-data-generator",
3
- "version": "0.3.0-alpha.3",
3
+ "version": "0.3.0-alpha.5",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/voces/graphql-data-generator.git"
@@ -35,6 +35,16 @@
35
35
  "bin": {
36
36
  "graphql-data-generator": "./esm/cli.js"
37
37
  },
38
+ "typesVersions": {
39
+ "*": {
40
+ "script/jest": [
41
+ "types/jest.d.ts"
42
+ ],
43
+ "script/plugin": [
44
+ "types/plugin.d.ts"
45
+ ]
46
+ }
47
+ },
38
48
  "dependencies": {
39
49
  "@graphql-codegen/visitor-plugin-common": "*",
40
50
  "fast-glob": "*",
package/script/jest.js CHANGED
@@ -23,12 +23,12 @@ var __importStar = (this && this.__importStar) || function (mod) {
23
23
  return result;
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.MockProvider = void 0;
26
+ exports.MockProvider = exports.failRefetchWarnings = void 0;
27
27
  const dntShim = __importStar(require("./_dnt.shims.js"));
28
28
  const react_1 = __importStar(require("react"));
29
29
  const client_1 = require("@apollo/client");
30
- const index_js_1 = require("@apollo/client/link/error/index.js");
31
- const index_js_2 = require("@apollo/client/testing/index.js");
30
+ const error_1 = require("@apollo/client/link/error");
31
+ const testing_1 = require("@apollo/client/testing");
32
32
  const dom_1 = require("@testing-library/dom");
33
33
  const graphql_1 = require("graphql");
34
34
  const jest_diff_1 = require("jest-diff");
@@ -38,18 +38,11 @@ jasmine.getEnv().addReporter({
38
38
  });
39
39
  const afterTest = [];
40
40
  afterEach(async () => {
41
- for (const hook of afterTest)
41
+ const hooks = afterTest.splice(0);
42
+ for (const hook of hooks)
42
43
  await hook();
43
- afterTest.splice(0);
44
44
  });
45
- const diff = (a, b) => (0, jest_diff_1.diff)(a, b, {
46
- omitAnnotationLines: true,
47
- // aColor: green,
48
- // bColor: red,
49
- // changeColor: inverse,
50
- // commonColor: dim,
51
- // patchColor: yellow,
52
- })
45
+ const diff = (a, b) => (0, jest_diff_1.diff)(a, b, { omitAnnotationLines: true })
53
46
  ?.replace(/\w+ \{/g, "{") // Remove class names
54
47
  .replace(/\w+ \[/g, "["); // Remove array class names
55
48
  const getErrorMessage = (operation, mockLink) => {
@@ -64,7 +57,7 @@ const getErrorMessage = (operation, mockLink) => {
64
57
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
65
58
  const alts = (mockLink
66
59
  .mockedResponsesByKey[key] ?? []);
67
- let errorMessage = `Expected GraphQL ${operationType} ${operation.operationName} to have been mocked`;
60
+ let errorMessage = `Expected ${operationType} ${operation.operationName} to have been mocked`;
68
61
  if (alts.length || Object.keys(operation.variables).length > 0) {
69
62
  errorMessage += ` with variables ${dntShim.Deno.inspect(operation.variables, { depth: Infinity, colors: true })}`;
70
63
  }
@@ -87,13 +80,39 @@ const getErrorMessage = (operation, mockLink) => {
87
80
  : undefined,
88
81
  };
89
82
  };
83
+ let _failRefetchWarnings = false;
84
+ /**
85
+ * In older versions of `@apollo/client`, refetches with missing mocks trigger
86
+ * warnings instead of being treated as standard missing mocks.
87
+ * This utility converts those warnings into failures and ensures watch queries
88
+ * are installed for queries with `watch: true`.
89
+ */
90
+ const failRefetchWarnings = (value = true) => _failRefetchWarnings = value;
91
+ exports.failRefetchWarnings = failRefetchWarnings;
92
+ const AutoWatch = ({ mocks }) => {
93
+ const client = (0, client_1.useApolloClient)();
94
+ for (const mock of mocks)
95
+ if (mock.watch)
96
+ client.watchQuery(mock.request);
97
+ return null;
98
+ };
90
99
  const MockProvider = ({ mocks, stack: renderStack, children }) => {
91
100
  const observableMocks = (0, react_1.useMemo)(() => {
92
- const observableMocks = mocks.map((m) => ({
93
- ...m,
94
- stack: m.stack,
95
- result: Object.assign(jest.fn(() => m.result), m.result),
96
- }));
101
+ const observableMocks = mocks.flatMap((m) => [
102
+ {
103
+ ...m,
104
+ stack: m.stack,
105
+ result: Object.assign(jest.fn(() => m.result), m.result),
106
+ },
107
+ ...(m.watch
108
+ ? [{
109
+ ...m,
110
+ stack: m.stack,
111
+ result: Object.assign(jest.fn(() => m.result), m.result),
112
+ watch: false,
113
+ }]
114
+ : []),
115
+ ]);
97
116
  afterTest.push(async () => {
98
117
  if (currentSpecResult.failedExpectations.length)
99
118
  return;
@@ -104,7 +123,8 @@ const MockProvider = ({ mocks, stack: renderStack, children }) => {
104
123
  if (currentSpecResult.failedExpectations.length)
105
124
  return;
106
125
  if (mock.result.mock.calls.length === 0) {
107
- const err = new Error(`Expected to have used mock${mock.request.variables
126
+ const operation = mock.request.query.definitions.find((d) => d.kind === graphql_1.Kind.OPERATION_DEFINITION);
127
+ const err = new Error(`Expected to have used ${operation?.operation} ${operation?.name?.value}${mock.request.variables
108
128
  ? ` with variables ${dntShim.Deno.inspect(mock.request.variables, {
109
129
  depth: Infinity,
110
130
  colors: true,
@@ -119,9 +139,9 @@ const MockProvider = ({ mocks, stack: renderStack, children }) => {
119
139
  return observableMocks;
120
140
  }, [mocks]);
121
141
  const link = (0, react_1.useMemo)(() => {
122
- const mockLink = new index_js_2.MockLink(observableMocks);
142
+ const mockLink = new testing_1.MockLink(observableMocks);
123
143
  mockLink.showWarnings = false;
124
- const errorLoggingLink = new index_js_1.ErrorLink(({ networkError, operation }) => {
144
+ const errorLoggingLink = new error_1.ErrorLink(({ networkError, operation }) => {
125
145
  if (!networkError?.message.includes("No more mocked responses"))
126
146
  return;
127
147
  const { message, stack: altStack } = getErrorMessage(operation, mockLink);
@@ -139,6 +159,31 @@ const MockProvider = ({ mocks, stack: renderStack, children }) => {
139
159
  // @ts-ignore It's fine
140
160
  return client_1.ApolloLink.from([errorLoggingLink, mockLink]);
141
161
  }, [observableMocks, renderStack]);
142
- return react_1.default.createElement(index_js_2.MockedProvider, { link: link }, children);
162
+ if (_failRefetchWarnings) {
163
+ const oldWarn = console.warn.bind(console.warn);
164
+ console.warn = (message, operation, ...etc) => {
165
+ if (message !==
166
+ 'Unknown query named "%s" requested in refetchQueries in options.include array') {
167
+ return oldWarn(message, operation, ...etc);
168
+ }
169
+ try {
170
+ fail({
171
+ name: "Error",
172
+ message: `Expected query ${operation} requested in refetchQueries options.include array to have bene mocked`,
173
+ stack: renderStack,
174
+ });
175
+ }
176
+ catch {
177
+ // eat
178
+ }
179
+ };
180
+ afterTest.push(() => {
181
+ console.warn = oldWarn;
182
+ });
183
+ }
184
+ return (react_1.default.createElement(testing_1.MockedProvider, { link: link },
185
+ react_1.default.createElement(react_1.default.Fragment, null,
186
+ react_1.default.createElement(AutoWatch, { mocks: observableMocks }),
187
+ children)));
143
188
  };
144
189
  exports.MockProvider = MockProvider;
package/types/jest.d.ts CHANGED
@@ -1,5 +1,12 @@
1
1
  import React from "react";
2
2
  import type { OperationMock } from "./types.js";
3
+ /**
4
+ * In older versions of `@apollo/client`, refetches with missing mocks trigger
5
+ * warnings instead of being treated as standard missing mocks.
6
+ * This utility converts those warnings into failures and ensures watch queries
7
+ * are installed for queries with `watch: true`.
8
+ */
9
+ export declare const failRefetchWarnings: (value?: boolean) => boolean;
3
10
  export declare const MockProvider: ({ mocks, stack: renderStack, children }: {
4
11
  mocks: OperationMock[];
5
12
  stack?: string;
package/types/types.d.ts CHANGED
@@ -28,6 +28,7 @@ export type OperationMock<Data extends Record<string, unknown> = Record<string,
28
28
  };
29
29
  error?: Error;
30
30
  stack?: string;
31
+ watch?: boolean;
31
32
  };
32
33
  export type SimpleOperationMock<Data extends Record<string, unknown> = Record<string, unknown>, Variables = Record<string, unknown> | never> = {
33
34
  data: Data;