From 0c6f67c8ecb638369aeba25c9459e9e3e351878c Mon Sep 17 00:00:00 2001 From: sam585456525 Date: Thu, 12 Oct 2023 18:15:33 +0800 Subject: [PATCH] refactor: test & custom-mapper query --- .../react-query/src/fetcher-custom-mapper.ts | 33 +- .../typescript/react-query/src/fetcher.ts | 4 +- .../__snapshots__/react-query.spec.ts.snap | 264 +++++++++++-- .../react-query/tests/react-query.spec.ts | 358 ++---------------- 4 files changed, 266 insertions(+), 393 deletions(-) diff --git a/packages/plugins/typescript/react-query/src/fetcher-custom-mapper.ts b/packages/plugins/typescript/react-query/src/fetcher-custom-mapper.ts index 11cd6eb5d..42a67778b 100644 --- a/packages/plugins/typescript/react-query/src/fetcher-custom-mapper.ts +++ b/packages/plugins/typescript/react-query/src/fetcher-custom-mapper.ts @@ -91,41 +91,18 @@ export class CustomMapperFetcher extends FetcherRenderer { } generateQueryHook(config: GenerateQueryHookConfig): string { - const { - node, - documentVariableName, - operationName, - operationResultType, - operationVariablesTypes, - hasRequiredVariables, - } = config; - - const variables = `variables${hasRequiredVariables ? '' : '?'}: ${operationVariablesTypes}`; - - const hookConfig = this.visitor.queryMethodMap; - this.visitor.reactQueryHookIdentifiersInUse.add(hookConfig.query.hook); - this.visitor.reactQueryOptionsIdentifiersInUse.add(hookConfig.query.options); + const { generateBaseQueryHook } = this.generateQueryHelper(config); - const options = `options?: ${hookConfig.query.options}<${operationResultType}, TError, TData>`; + const { documentVariableName, operationResultType, operationVariablesTypes } = config; const typedFetcher = this.getFetcherFnName(operationResultType, operationVariablesTypes); const impl = this._isReactHook ? `${typedFetcher}(${documentVariableName}).bind(null, variables)` : `${typedFetcher}(${documentVariableName}, variables)`; - return `export const use${operationName} = < - TData = ${operationResultType}, - TError = ${this.visitor.config.errorType} - >( - ${variables}, - ${options} - ) => - ${hookConfig.query.hook}<${operationResultType}, TError, TData>( - ${this.generateQueryFormattedParameters( - this.generateQueryKey(node, hasRequiredVariables), - impl, - )} - );`; + return generateBaseQueryHook({ + implFetcher: impl, + }); } generateMutationHook( diff --git a/packages/plugins/typescript/react-query/src/fetcher.ts b/packages/plugins/typescript/react-query/src/fetcher.ts index 467c030a9..df0c0e744 100644 --- a/packages/plugins/typescript/react-query/src/fetcher.ts +++ b/packages/plugins/typescript/react-query/src/fetcher.ts @@ -40,12 +40,12 @@ export class BaseFetcherRenderer { implHookOuter?: string; implFetcher: string; }) => { - const { implArguments = '', implHookOuter = '', implFetcher = '' } = config; + const { implArguments, implHookOuter = '', implFetcher } = config; const argumentsResult = implArguments ?? `${variables}, - ${options}`; + ${options}`; return `export const use${operationName} = < TData = ${operationResultType}, diff --git a/packages/plugins/typescript/react-query/tests/__snapshots__/react-query.spec.ts.snap b/packages/plugins/typescript/react-query/tests/__snapshots__/react-query.spec.ts.snap index bf8a778b8..d4d4692f7 100644 --- a/packages/plugins/typescript/react-query/tests/__snapshots__/react-query.spec.ts.snap +++ b/packages/plugins/typescript/react-query/tests/__snapshots__/react-query.spec.ts.snap @@ -25,7 +25,7 @@ export const useTestQuery = < variables?: TestQueryVariables, options?: UseQueryOptions ) => { - + return useQuery( variables === undefined ? ['test'] : ['test', variables], fetcher(dataSource.endpoint, dataSource.fetchParams || {}, TestDocument, variables), @@ -81,7 +81,7 @@ export const useTestQuery = < variables?: TestQueryVariables, options?: UseQueryOptions ) => { - + return useQuery( variables === undefined ? ['test'] : ['test', variables], fetcher(dataSource.endpoint, dataSource.fetchParams || {}, TestDocument, variables), @@ -155,7 +155,7 @@ export const useTestQuery = < variables?: TestQueryVariables, options?: UseQueryOptions ) => { - + return useQuery( variables === undefined ? ['test'] : ['test', variables], fetcher(dataSource.endpoint, dataSource.fetchParams || {}, TestDocument, variables), @@ -210,7 +210,7 @@ export const useTestQuery = < variables?: TestQueryVariables, options?: UseQueryOptions ) => { - + return useQuery( variables === undefined ? ['test'] : ['test', variables], fetcher(dataSource.endpoint, dataSource.fetchParams || {}, TestDocument, variables), @@ -257,7 +257,7 @@ export const useTestMutation = < );" `; -exports[`React-Query fetcher: custom-mapper Should generate mutation correctly with lazy variables 1`] = ` +exports[`React-Query fetcher: custom-mapper Should generate mutation correctly with lazy variables: content 1`] = ` " export const TestDocument = \` query test { @@ -280,12 +280,13 @@ export const useTestQuery = < >( variables?: TTestQueryVariables, options?: UseQueryOptions - ) => - useQuery( + ) => { + + return useQuery( variables === undefined ? ['test'] : ['test', variables], useCustomFetcher(TestDocument).bind(null, variables), options - ); + )}; export const useInfiniteTestQuery = < TData = TTestQuery, TError = unknown @@ -318,7 +319,14 @@ export const useTestMutation = < );" `; -exports[`React-Query fetcher: custom-mapper Should generate query correctly with external mapper 1`] = ` +exports[`React-Query fetcher: custom-mapper Should generate mutation correctly with lazy variables: prepend 1`] = ` +[ + "import { useQuery, useInfiniteQuery, useMutation, UseQueryOptions, UseInfiniteQueryOptions, UseMutationOptions } from 'react-query';", + "import { useCustomFetcher } from './my-file';", +] +`; + +exports[`React-Query fetcher: custom-mapper Should generate query correctly with external mapper: content 1`] = ` " export const TestDocument = \` query test { @@ -341,12 +349,13 @@ export const useTestQuery = < >( variables?: TTestQueryVariables, options?: UseQueryOptions - ) => - useQuery( + ) => { + + return useQuery( variables === undefined ? ['test'] : ['test', variables], myCustomFetcher(TestDocument, variables), options - ); + )}; export const useInfiniteTestQuery = < TData = TTestQuery, TError = unknown @@ -354,7 +363,7 @@ export const useInfiniteTestQuery = < variables?: TTestQueryVariables, options?: UseInfiniteQueryOptions ) =>{ - + return useInfiniteQuery( variables === undefined ? ['test.infinite'] : ['test.infinite', variables], (metaData) => myCustomFetcher(TestDocument, {...variables, ...(metaData.pageParam ?? {})})(), @@ -379,7 +388,14 @@ export const useTestMutation = < );" `; -exports[`React-Query fetcher: custom-mapper Should generate query correctly with internal mapper 1`] = ` +exports[`React-Query fetcher: custom-mapper Should generate query correctly with external mapper: prepend 1`] = ` +[ + "import { useQuery, useInfiniteQuery, useMutation, UseQueryOptions, UseInfiniteQueryOptions, UseMutationOptions } from 'react-query';", + "import { myCustomFetcher } from './my-file';", +] +`; + +exports[`React-Query fetcher: custom-mapper Should generate query correctly with internal mapper: content 1`] = ` " export const TestDocument = \` query test { @@ -402,12 +418,13 @@ export const useTestQuery = < >( variables?: TTestQueryVariables, options?: UseQueryOptions - ) => - useQuery( + ) => { + + return useQuery( variables === undefined ? ['test'] : ['test', variables], myCustomFetcher(TestDocument, variables), options - ); + )}; export const TestDocument = \` mutation test($name: String) { submitRepository(repoFullName: $name) { @@ -426,6 +443,13 @@ export const useTestMutation = < );" `; +exports[`React-Query fetcher: custom-mapper Should generate query correctly with internal mapper: prepend 1`] = ` +[ + "import { useQuery, useMutation, UseQueryOptions, UseMutationOptions } from 'react-query';", + null, +] +`; + exports[`React-Query fetcher: fetch Should generate query and mutation correctly: content 1`] = ` " export const TestDocument = \` @@ -451,7 +475,7 @@ export const useTestQuery = < variables?: TTestQueryVariables, options?: UseQueryOptions ) => { - + return useQuery( variables === undefined ? ['test'] : ['test', variables], fetcher(dataSource.endpoint, dataSource.fetchParams || {}, TestDocument, variables), @@ -504,7 +528,7 @@ function fetcher(endpoint: string, requestInit: RequestInit, ] `; -exports[`React-Query fetcher: graphql-request Should generate query correctly with client 1`] = ` +exports[`React-Query fetcher: graphql-request Should generate query correctly with client: content 1`] = ` " export const TestDocument = \` query test { @@ -557,7 +581,23 @@ export const useTestMutation = < );" `; -exports[`React-Query fetcher: graphql-request with clientImportPath Should generate query correctly with client 1`] = ` +exports[`React-Query fetcher: graphql-request Should generate query correctly with client: prepend 1`] = ` +[ + "import { GraphQLClient } from 'graphql-request';", + "import { RequestInit } from 'graphql-request/dist/types.dom';", + "import { useQuery, useMutation, UseQueryOptions, UseMutationOptions } from 'react-query';", + " +function fetcher(client: GraphQLClient, query: string, variables?: TVariables, requestHeaders?: RequestInit['headers']) { + return async (): Promise => client.request({ + document: query, + variables, + requestHeaders + }); +}", +] +`; + +exports[`React-Query fetcher: graphql-request with clientImportPath Should generate query correctly with client: content 1`] = ` " export const TestDocument = \` query test { @@ -608,7 +648,24 @@ export const useTestMutation = < );" `; -exports[`React-Query fetcher: hardcoded-fetch Should generate query correctly with fetch config 2`] = ` +exports[`React-Query fetcher: graphql-request with clientImportPath Should generate query correctly with client: prepend 1`] = ` +[ + "import { client as graphqlClient } from 'client.ts';", + "import { GraphQLClient } from 'graphql-request';", + "import { RequestInit } from 'graphql-request/dist/types.dom';", + "import { useQuery, useMutation, UseQueryOptions, UseMutationOptions } from 'react-query';", + " +function fetcher(query: string, variables?: TVariables, requestHeaders?: RequestInit['headers']) { + return async (): Promise => graphqlClient.request({ + document: query, + variables, + requestHeaders + }); +}", +] +`; + +exports[`React-Query fetcher: hardcoded-fetch Should generate query correctly with fetch config and fetchParams object: content 1`] = ` " export const TestDocument = \` query test { @@ -655,7 +712,33 @@ export const useTestMutation = < );" `; -exports[`React-Query fetcher: hardcoded-fetch Should generate query correctly with fetch config and fetchParams object 2`] = ` +exports[`React-Query fetcher: hardcoded-fetch Should generate query correctly with fetch config and fetchParams object: prepend 1`] = ` +[ + "import { useQuery, useMutation, UseQueryOptions, UseMutationOptions } from '@tanstack/react-query';", + " +function fetcher(query: string, variables?: TVariables) { + return async (): Promise => { + const res = await fetch("http://localhost:3000/graphql", { + method: "POST", + ...({"headers":{"Authorization":"Bearer XYZ"}}), + body: JSON.stringify({ query, variables }), + }); + + const json = await res.json(); + + if (json.errors) { + const { message } = json.errors[0]; + + throw new Error(message); + } + + return json.data; + } +}", +] +`; + +exports[`React-Query fetcher: hardcoded-fetch Should generate query correctly with fetch config: content 1`] = ` " export const TestDocument = \` query test { @@ -702,7 +785,33 @@ export const useTestMutation = < );" `; -exports[`React-Query fetcher: hardcoded-fetch Should generate query correctly with hardcoded endpoint 1`] = ` +exports[`React-Query fetcher: hardcoded-fetch Should generate query correctly with fetch config: prepend 1`] = ` +[ + "import { useQuery, useMutation, UseQueryOptions, UseMutationOptions } from '@tanstack/react-query';", + " +function fetcher(query: string, variables?: TVariables) { + return async (): Promise => { + const res = await fetch("http://localhost:3000/graphql", { + method: "POST", + ...({"headers":{"Authorization":"Bearer XYZ"}}), + body: JSON.stringify({ query, variables }), + }); + + const json = await res.json(); + + if (json.errors) { + const { message } = json.errors[0]; + + throw new Error(message); + } + + return json.data; + } +}", +] +`; + +exports[`React-Query fetcher: hardcoded-fetch Should generate query correctly with hardcoded endpoint from env var: content 1`] = ` " export const TestDocument = \` query test { @@ -749,7 +858,32 @@ export const useTestMutation = < );" `; -exports[`React-Query fetcher: hardcoded-fetch Should generate query correctly with hardcoded endpoint from env var 1`] = ` +exports[`React-Query fetcher: hardcoded-fetch Should generate query correctly with hardcoded endpoint from env var: prepend 1`] = ` +[ + "import { useQuery, useMutation, UseQueryOptions, UseMutationOptions } from '@tanstack/react-query';", + " +function fetcher(query: string, variables?: TVariables) { + return async (): Promise => { + const res = await fetch(process.env.ENDPOINT_URL as string, { + method: "POST", + body: JSON.stringify({ query, variables }), + }); + + const json = await res.json(); + + if (json.errors) { + const { message } = json.errors[0]; + + throw new Error(message); + } + + return json.data; + } +}", +] +`; + +exports[`React-Query fetcher: hardcoded-fetch Should generate query correctly with hardcoded endpoint from just identifier: content 1`] = ` " export const TestDocument = \` query test { @@ -796,7 +930,32 @@ export const useTestMutation = < );" `; -exports[`React-Query fetcher: hardcoded-fetch Should generate query correctly with hardcoded endpoint from just identifier 1`] = ` +exports[`React-Query fetcher: hardcoded-fetch Should generate query correctly with hardcoded endpoint from just identifier: prepend 1`] = ` +[ + "import { useQuery, useMutation, UseQueryOptions, UseMutationOptions } from '@tanstack/react-query';", + " +function fetcher(query: string, variables?: TVariables) { + return async (): Promise => { + const res = await fetch(myEndpoint as string, { + method: "POST", + body: JSON.stringify({ query, variables }), + }); + + const json = await res.json(); + + if (json.errors) { + const { message } = json.errors[0]; + + throw new Error(message); + } + + return json.data; + } +}", +] +`; + +exports[`React-Query fetcher: hardcoded-fetch Should generate query correctly with hardcoded endpoint: content 1`] = ` " export const TestDocument = \` query test { @@ -843,6 +1002,57 @@ export const useTestMutation = < );" `; +exports[`React-Query fetcher: hardcoded-fetch Should generate query correctly with hardcoded endpoint: prepend 1`] = ` +[ + "import { useQuery, useMutation, UseQueryOptions, UseMutationOptions } from 'react-query';", + " +function fetcher(query: string, variables?: TVariables) { + return async (): Promise => { + const res = await fetch("http://localhost:3000/graphql", { + method: "POST", + body: JSON.stringify({ query, variables }), + }); + + const json = await res.json(); + + if (json.errors) { + const { message } = json.errors[0]; + + throw new Error(message); + } + + return json.data; + } +}", +] +`; + +exports[`React-Query reactQueryImportFrom: custom-path Should import react-query from custom path: prepend 1`] = ` +[ + "import { useQuery, useMutation, UseQueryOptions, UseMutationOptions } from 'custom-react-query';", + " +function fetcher(endpoint: string, requestInit: RequestInit, query: string, variables?: TVariables) { + return async (): Promise => { + const res = await fetch(endpoint, { + method: 'POST', + ...requestInit, + body: JSON.stringify({ query, variables }), + }); + + const json = await res.json(); + + if (json.errors) { + const { message } = json.errors[0]; + + throw new Error(message); + } + + return json.data; + } +}", +] +`; + exports[`React-Query support v4 syntax: content 1`] = ` " export const TestDocument = \` @@ -868,7 +1078,7 @@ export const useTestQuery = < variables?: TestQueryVariables, options?: UseQueryOptions ) => { - + return useQuery( variables === undefined ? ['test'] : ['test', variables], fetcher(dataSource.endpoint, dataSource.fetchParams || {}, TestDocument, variables), @@ -960,7 +1170,7 @@ export const useTestQuery = < variables?: TestQueryVariables, options?: UseQueryOptions ) => { - + return useQuery( { queryKey: variables === undefined ? ['test'] : ['test', variables], diff --git a/packages/plugins/typescript/react-query/tests/react-query.spec.ts b/packages/plugins/typescript/react-query/tests/react-query.spec.ts index 184a74442..a5b7ad620 100644 --- a/packages/plugins/typescript/react-query/tests/react-query.spec.ts +++ b/packages/plugins/typescript/react-query/tests/react-query.spec.ts @@ -186,47 +186,8 @@ describe('React-Query', () => { const out = (await plugin(schema, docs, config)) as Types.ComplexPluginOutput; - expect(out.prepend).toContain( - `import { useQuery, useInfiniteQuery, useMutation, UseQueryOptions, UseInfiniteQueryOptions, UseMutationOptions } from 'react-query';`, - ); - - expect(out.prepend).toContain(`import { myCustomFetcher } from './my-file';`); - expect(out.content).toBeSimilarStringTo(`export const useTestQuery = < - TData = TTestQuery, - TError = unknown - >( - variables?: TTestQueryVariables, - options?: UseQueryOptions - ) => - useQuery( - variables === undefined ? ['test'] : ['test', variables], - myCustomFetcher(TestDocument, variables), - options - );`); - - expect(out.content).toBeSimilarStringTo(`export const useInfiniteTestQuery = < - TData = TTestQuery, - TError = unknown - >( - variables?: TTestQueryVariables, - options?: UseInfiniteQueryOptions - ) =>{ - return useInfiniteQuery( - variables === undefined ? ['test.infinite'] : ['test.infinite', variables], - (metaData) => myCustomFetcher(TestDocument, {...variables, ...(metaData.pageParam ?? {})})(), - options - )};`); - expect(out.content).toBeSimilarStringTo(`export const useTestMutation = < - TError = unknown, - TContext = unknown - >(options?: UseMutationOptions) => - useMutation( - ['test'], - (variables?: TTestMutationVariables) => myCustomFetcher(TestDocument, variables)(), - options - );`); - - expect(out.content).toMatchSnapshot(); + expect(out.prepend).toMatchSnapshot('prepend'); + expect(out.content).toMatchSnapshot('content'); await validateTypeScript(mergeOutputs(out), schema, docs, config); }); @@ -239,33 +200,8 @@ describe('React-Query', () => { const out = (await plugin(schema, docs, config)) as Types.ComplexPluginOutput; - expect(out.prepend).toContain( - `import { useQuery, useMutation, UseQueryOptions, UseMutationOptions } from 'react-query';`, - ); - expect(out.content).toBeSimilarStringTo(`export const useTestQuery = < - TData = TTestQuery, - TError = unknown - >( - variables?: TTestQueryVariables, - options?: UseQueryOptions - ) => - useQuery( - variables === undefined ? ['test'] : ['test', variables], - myCustomFetcher(TestDocument, variables), - options - );`); - - expect(out.content).toBeSimilarStringTo(`export const useTestMutation = < - TError = unknown, - TContext = unknown - >(options?: UseMutationOptions) => - useMutation( - ['test'], - (variables?: TTestMutationVariables) => myCustomFetcher(TestDocument, variables)(), - options - );`); - - expect(out.content).toMatchSnapshot(); + expect(out.prepend).toMatchSnapshot('prepend'); + expect(out.content).toMatchSnapshot('content'); await validateTypeScript(mergeOutputs(out), schema, docs, config); }); @@ -282,47 +218,8 @@ describe('React-Query', () => { const out = (await plugin(schema, docs, config)) as Types.ComplexPluginOutput; - expect(out.prepend).toContain( - `import { useQuery, useInfiniteQuery, useMutation, UseQueryOptions, UseInfiniteQueryOptions, UseMutationOptions } from 'react-query';`, - ); - expect(out.prepend).toContain(`import { useCustomFetcher } from './my-file';`); - expect(out.content).toBeSimilarStringTo(`export const useTestQuery = < - TData = TTestQuery, - TError = unknown - >( - variables?: TTestQueryVariables, - options?: UseQueryOptions - ) => - useQuery( - variables === undefined ? ['test'] : ['test', variables], - useCustomFetcher(TestDocument).bind(null, variables), - options - );`); - - expect(out.content).toBeSimilarStringTo(`export const useInfiniteTestQuery = < - TData = TTestQuery, - TError = unknown - >( - variables?: TTestQueryVariables, - options?: UseInfiniteQueryOptions - ) =>{ - const query = useCustomFetcher(TestDocument) - return useInfiniteQuery( - variables === undefined ? ['test.infinite'] : ['test.infinite', variables], - (metaData) => query({...variables, ...(metaData.pageParam ?? {})}), - options - )};`); - expect(out.content).toBeSimilarStringTo(`export const useTestMutation = < - TError = unknown, - TContext = unknown - >(options?: UseMutationOptions) => - useMutation( - ['test'], - useCustomFetcher(TestDocument), - options - );`); - - expect(out.content).toMatchSnapshot(); + expect(out.prepend).toMatchSnapshot('prepend'); + expect(out.content).toMatchSnapshot('content'); await validateTypeScript(mergeOutputs(out), schema, docs, config); }); @@ -522,49 +419,8 @@ describe('React-Query', () => { const out = (await plugin(schema, docs, config)) as Types.ComplexPluginOutput; - expect(out.prepend).toContain( - `import { useQuery, useMutation, UseQueryOptions, UseMutationOptions } from 'react-query';`, - ); - expect(out.prepend).toContain(`import { GraphQLClient } from 'graphql-request';`); - expect(out.prepend).toContain( - `import { RequestInit } from 'graphql-request/dist/types.dom';`, - ); - expect(out.prepend[3]) - .toBeSimilarStringTo(` function fetcher(client: GraphQLClient, query: string, variables?: TVariables, requestHeaders?: RequestInit['headers']) { - return async (): Promise => client.request({ - document: query, - variables, - requestHeaders - `); - expect(out.content).toBeSimilarStringTo(`export const useTestQuery = < - TData = TTestQuery, - TError = unknown - >( - client: GraphQLClient, - variables?: TTestQueryVariables, - options?: UseQueryOptions, - headers?: RequestInit['headers'] - ) => - useQuery( - variables === undefined ? ['test'] : ['test', variables], - fetcher(client, TestDocument, variables, headers), - options - );`); - expect(out.content).toBeSimilarStringTo(`export const useTestMutation = < - TError = unknown, - TContext = unknown - >( - client: GraphQLClient, - options?: UseMutationOptions, - headers?: RequestInit['headers'] - ) => - useMutation( - ['test'], - (variables?: TTestMutationVariables) => fetcher(client, TestDocument, variables, headers)(), - options - );`); - - expect(out.content).toMatchSnapshot(); + expect(out.prepend).toMatchSnapshot('prepend'); + expect(out.content).toMatchSnapshot('content'); await validateTypeScript(mergeOutputs(out), schema, docs, config); }); it('Should support useTypeImports', async () => { @@ -713,48 +569,8 @@ describe('React-Query', () => { const out = (await plugin(schema, docs, config)) as Types.ComplexPluginOutput; - expect(out.prepend).toContain( - `import { useQuery, useMutation, UseQueryOptions, UseMutationOptions } from 'react-query';`, - ); - expect(out.prepend).toContain(clientImportPath); - expect(out.prepend).toContain(`import { GraphQLClient } from 'graphql-request';`); - expect(out.prepend).toContain( - `import { RequestInit } from 'graphql-request/dist/types.dom';`, - ); - expect(out.prepend[4]) - .toBeSimilarStringTo(` function fetcher(query: string, variables?: TVariables, requestHeaders?: RequestInit['headers']) { - return async (): Promise => graphqlClient.request({ - document: query, - variables, - requestHeaders - `); - expect(out.content).toBeSimilarStringTo(`export const useTestQuery = < - TData = TTestQuery, - TError = unknown - >( - variables?: TTestQueryVariables, - options?: UseQueryOptions, - headers?: RequestInit['headers'] - ) => - useQuery( - variables === undefined ? ['test'] : ['test', variables], - fetcher(TestDocument, variables, headers), - options - );`); - expect(out.content).toBeSimilarStringTo(`export const useTestMutation = < - TError = unknown, - TContext = unknown - >( - options?: UseMutationOptions, - headers?: RequestInit['headers'] - ) => - useMutation( - ['test'], - (variables?: TTestMutationVariables) => fetcher(TestDocument, variables, headers)(), - options - );`); - - expect(out.content).toMatchSnapshot(); + expect(out.prepend).toMatchSnapshot('prepend'); + expect(out.content).toMatchSnapshot('content'); await validateTypeScript(mergeOutputs(out), schema, docs, config); }); it('Should generate fetcher field when exposeFetcher is true', async () => { @@ -784,52 +600,8 @@ describe('React-Query', () => { const out = (await plugin(schema, docs, config)) as Types.ComplexPluginOutput; - expect(out.prepend).toContain( - `import { useQuery, useMutation, UseQueryOptions, UseMutationOptions } from 'react-query';`, - ); - expect(out.prepend[1]) - .toBeSimilarStringTo(` function fetcher(query: string, variables?: TVariables) { - return async (): Promise => { - const res = await fetch("http://localhost:3000/graphql", { - method: "POST", - body: JSON.stringify({ query, variables }), - }); - - const json = await res.json(); - - if (json.errors) { - const { message } = json.errors[0]; - - throw new Error(message); - } - - return json.data; - } - }`); - expect(out.content).toBeSimilarStringTo(`export const useTestQuery = < - TData = TTestQuery, - TError = unknown - >( - variables?: TTestQueryVariables, - options?: UseQueryOptions - ) => - useQuery( - variables === undefined ? ['test'] : ['test', variables], - fetcher(TestDocument, variables), - options - );`); - - expect(out.content).toBeSimilarStringTo(`export const useTestMutation = < - TError = unknown, - TContext = unknown - >(options?: UseMutationOptions) => - useMutation( - ['test'], - (variables?: TTestMutationVariables) => fetcher(TestDocument, variables)(), - options - );`); - - expect(out.content).toMatchSnapshot(); + expect(out.prepend).toMatchSnapshot('prepend'); + expect(out.content).toMatchSnapshot('content'); await validateTypeScript(mergeOutputs(out), schema, docs, config); }); @@ -848,30 +620,8 @@ describe('React-Query', () => { const out = (await plugin(schema, docs, config)) as Types.ComplexPluginOutput; - expect(out.prepend[1]).toMatchInlineSnapshot(` - " - function fetcher(query: string, variables?: TVariables) { - return async (): Promise => { - const res = await fetch("http://localhost:3000/graphql", { - method: "POST", - ...({"headers":{"Authorization":"Bearer XYZ"}}), - body: JSON.stringify({ query, variables }), - }); - - const json = await res.json(); - - if (json.errors) { - const { message } = json.errors[0]; - - throw new Error(message); - } - - return json.data; - } - }" - `); - - expect(out.content).toMatchSnapshot(); + expect(out.prepend).toMatchSnapshot('prepend'); + expect(out.content).toMatchSnapshot('content'); await validateTypeScript(mergeOutputs(out), schema, docs, config); }); @@ -890,30 +640,8 @@ describe('React-Query', () => { const out = (await plugin(schema, docs, config)) as Types.ComplexPluginOutput; - expect(out.prepend[1]).toMatchInlineSnapshot(` - " - function fetcher(query: string, variables?: TVariables) { - return async (): Promise => { - const res = await fetch("http://localhost:3000/graphql", { - method: "POST", - ...({"headers":{"Authorization":"Bearer XYZ"}}), - body: JSON.stringify({ query, variables }), - }); - - const json = await res.json(); - - if (json.errors) { - const { message } = json.errors[0]; - - throw new Error(message); - } - - return json.data; - } - }" - `); - - expect(out.content).toMatchSnapshot(); + expect(out.prepend).toMatchSnapshot('prepend'); + expect(out.content).toMatchSnapshot('content'); await validateTypeScript(mergeOutputs(out), schema, docs, config); }); @@ -927,27 +655,8 @@ describe('React-Query', () => { const out = (await plugin(schema, docs, config)) as Types.ComplexPluginOutput; - expect(out.prepend[1]) - .toBeSimilarStringTo(`function fetcher(query: string, variables?: TVariables) { - return async (): Promise => { - const res = await fetch(process.env.ENDPOINT_URL as string, { - method: "POST", - body: JSON.stringify({ query, variables }), - }); - - const json = await res.json(); - - if (json.errors) { - const { message } = json.errors[0]; - - throw new Error(message); - } - - return json.data; - } - }`); - - expect(out.content).toMatchSnapshot(); + expect(out.prepend).toMatchSnapshot('prepend'); + expect(out.content).toMatchSnapshot('content'); await validateTypeScript(mergeOutputs(out), schema, docs, config); }); @@ -961,27 +670,8 @@ describe('React-Query', () => { const out = (await plugin(schema, docs, config)) as Types.ComplexPluginOutput; - expect(out.prepend[1]) - .toBeSimilarStringTo(` function fetcher(query: string, variables?: TVariables) { - return async (): Promise => { - const res = await fetch(myEndpoint as string, { - method: "POST", - body: JSON.stringify({ query, variables }), - }); - - const json = await res.json(); - - if (json.errors) { - const { message } = json.errors[0]; - - throw new Error(message); - } - - return json.data; - } - }`); - - expect(out.content).toMatchSnapshot(); + expect(out.prepend).toMatchSnapshot('prepend'); + expect(out.content).toMatchSnapshot('content'); await validateTypeScript(mergeOutputs(out), schema, docs, config); }); @@ -1363,12 +1053,8 @@ describe('React-Query', () => { reactQueryImportFrom: 'custom-react-query', }; const out = (await plugin(schema, docs, config)) as Types.ComplexPluginOutput; - expect(out.prepend).toContain( - "import { useQuery, useMutation, UseQueryOptions, UseMutationOptions } from 'custom-react-query';", - ); - expect(out.prepend).not.toContain( - `"import { useQuery, useMutation, UseQueryOptions, UseMutationOptions } from 'react-query';"`, - ); + expect(out.prepend).toMatchSnapshot('prepend'); + await validateTypeScript(mergeOutputs(out), schema, docs, config); }); }); });