-
Notifications
You must be signed in to change notification settings - Fork 45
/
testers.ts
244 lines (210 loc) · 6.55 KB
/
testers.ts
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
import * as PrismaSDK from '@prisma/sdk'
import dedent from 'dedent'
import execa from 'execa'
import * as fs from 'fs-jetpack'
import { DocumentNode, execute, printSchema } from 'graphql'
import { core } from 'nexus'
import { AllNexusTypeDefs } from 'nexus/dist/core'
import { generateRuntime } from '../../src/generator/generate'
import { Gentime } from '../../src/generator/gentime/settingsSingleton'
import * as ModelsGenerator from '../../src/generator/models'
import { Settings } from '../../src/generator/models/javascript'
import { Runtime } from '../../src/generator/runtime/settingsSingleton'
import { ModuleSpec } from '../../src/generator/types'
const settingsDefaults: Settings = {
gentime: Gentime.settings.data,
internal: { prismaClientImport: '@prisma/client' },
runtime: Runtime.settings,
}
/**
* Define Nexus type definitions based on the Nexus Prisma configurations
*
* The configurations are typed as `any` to make them easy to work with. They ae not typesafe. Be careful.
*/
type APISchemaSpec = (nexusPrisma: any) => AllNexusTypeDefs[]
export type IntegrationTestSpec = {
/**
* Name of this test
*/
description: string
/**
* Define a Prisma schema file
*
* Note datasource and generator blocks are taken care of automatically for you.
*/
datasourceSchema: string
apiSchema: APISchemaSpec
datasourceSeed: (prismaClient: any) => Promise<void>
apiClientQuery: DocumentNode
}
type IntegrationTestParams = IntegrationTestSpec & {
/**
* Proxy for it.only
*/
only?: boolean
/**
* Proxy for it.skip
*/
skip?: boolean
}
/**
* Test that the given Prisma schema generates the expected generated source code.
*/
export function testGeneratedModules(params: { databaseSchema: string; description: string }) {
it(params.description, async () => {
const { indexdts } = await generateModules(params.databaseSchema)
expect(indexdts).toMatchSnapshot('index.d.ts')
})
}
/**
* Test that the given Prisma schema + API Schema + data seed + GraphQL document lead to the expected
* GraphQL schema and execution result.
*/
export function testIntegration(params: IntegrationTestParams) {
if (params.skip && params.only)
throw new Error(`Cannot specify to skip this test AND only run this test at the same time.`)
const itOrItOnlyOrItSkip = params.only ? it.only : params.skip ? it.skip : it
itOrItOnlyOrItSkip(params.description, async () => {
const result = await integrationTest(params)
expect(result.graphqlSchemaSDL).toMatchSnapshot(`graphqlSchemaSDL`)
expect(result.graphqlOperationExecutionResult).toMatchSnapshot(`graphqlOperationExecutionResult`)
})
}
/**
* Test that the given Prisma schema + API Scheam lead to the expected GraphQL schema.
*/
export function testGraphqlSchema(params: {
datasourceSchema: string
description: string
apiSchema: APISchemaSpec
}) {
it(params.description, async () => {
const dmmf = await PrismaSDK.getDMMF({
datamodel: createPrismaSchema({ content: params.datasourceSchema }),
})
const nexusPrisma = ModelsGenerator.JS.createNexusTypeDefConfigurations(dmmf, settingsDefaults) as any
const { schema } = await core.generateSchema.withArtifacts({
types: params.apiSchema(nexusPrisma),
})
expect(prepareGraphQLSDLForSnapshot(printSchema(schema))).toMatchSnapshot('graphqlSchema')
})
}
/**
* Low Level
*/
export function createPrismaSchema({
content,
datasourceProvider = {
provider: 'postgres',
url: 'env("DB_URL")',
},
clientOutput,
nexusPrisma = true,
}: {
content: string
datasourceProvider?: { provider: 'sqlite'; url: string } | { provider: 'postgres'; url: string }
clientOutput?: string
nexusPrisma?: boolean
}): string {
return dedent`
datasource db {
provider = "${datasourceProvider.provider}"
url = ${datasourceProvider.url}
}
generator client {
provider = "prisma-client-js"${clientOutput ? `\noutput = ${clientOutput}` : ''}
}
${
nexusPrisma
? dedent`
generator nexusPrisma {
provider = "nexus-prisma"
}
`
: ``
}
${content}
`
}
/**
* Given a Prisma schema and Nexus type definitions return a GraphQL schema.
*/
export async function integrationTest({
datasourceSchema,
apiSchema,
datasourceSeed,
apiClientQuery,
}: IntegrationTestParams) {
const dir = fs.tmpDir().cwd()
const prismaClientImportId = `${dir}/client`
const prismaSchemaContents = createPrismaSchema({
content: datasourceSchema,
datasourceProvider: {
provider: 'sqlite',
url: `"file:./db.sqlite"`,
},
nexusPrisma: false,
clientOutput: `"./client"`,
})
fs.write(`${dir}/schema.prisma`, prismaSchemaContents)
execa.commandSync(`yarn -s prisma db push --force-reset --schema ${dir}/schema.prisma`)
const prismaClientPackage = require(prismaClientImportId)
const prismaClient = new prismaClientPackage.PrismaClient()
await datasourceSeed(prismaClient)
const dmmf = await PrismaSDK.getDMMF({
datamodel: prismaSchemaContents,
})
const nexusPrisma = ModelsGenerator.JS.createNexusTypeDefConfigurations(dmmf, {
...settingsDefaults,
internal: {
prismaClientImport: prismaClientImportId,
},
}) as any
const { schema } = await core.generateSchema.withArtifacts({
types: apiSchema(nexusPrisma),
})
const graphqlOperationExecutionResult = await execute({
contextValue: {
prisma: prismaClient,
},
schema: schema,
document: apiClientQuery,
})
await prismaClient.$disconnect()
if (graphqlOperationExecutionResult.errors) {
throw new Error(
`GraphQL operation failed:\n\n - ${graphqlOperationExecutionResult.errors.join('\n - ')}`
)
}
return {
graphqlSchemaSDL: prepareGraphQLSDLForSnapshot(printSchema(schema)),
graphqlOperationExecutionResult,
}
}
function prepareGraphQLSDLForSnapshot(sdl: string): string {
return '\n' + stripNexusQueryOk(sdl).trim() + '\n'
}
function stripNexusQueryOk(sdl: string): string {
return sdl.replace(
dedent`
type Query {
ok: Boolean!
}
`,
''
)
}
/**
* For the given Prisma Schema generate the derived source code.
*/
export async function generateModules(content: string): Promise<{ indexjs: string; indexdts: string }> {
const prismaSchemaContents = createPrismaSchema({ content })
const dmmf = await PrismaSDK.getDMMF({
datamodel: prismaSchemaContents,
})
const [indexjs, indexdts] = generateRuntime(dmmf, Gentime.settings) as [ModuleSpec, ModuleSpec]
return {
indexdts: indexdts.content,
indexjs: indexjs.content,
}
}