-
Notifications
You must be signed in to change notification settings - Fork 0
/
jest.setup.ts
143 lines (123 loc) · 3.88 KB
/
jest.setup.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
import { Prisma } from '@prisma/client'
import { version as clientVersion } from '@prisma/client/package.json'
import { PrismaClientKnownRequestError } from '@prisma/client/runtime/library'
import { MongoMemoryServer } from 'mongodb-memory-server'
import mongoose from 'mongoose'
import nock from 'nock'
import type { Delegate } from 'prismock/build/main/lib/delegate'
import { prisma } from './src/adapters/prisma/client'
import connect from './src/helpers/db/initDatabase'
jest.mock('winston')
jest.mock('@prisma/client', () => ({
...jest.requireActual('@prisma/client'),
PrismaClient: jest.requireActual('prismock').PrismockClient,
}))
jest.mock('./src/features/authentication/authentication.service', () => ({
...jest.requireActual('./src/features/authentication/authentication.service'),
generateVerificationCodeAndExpiration: jest.fn(),
}))
const models = Prisma.dmmf.datamodel.models
.map(({ name }) => ({
name,
delegateKey: name.replace(/(?:^\w|[A-Z]|\b\w)/g, (word, index) =>
index === 0 ? word.toLowerCase() : word.toUpperCase()
),
}))
.map(({ name, delegateKey }) => ({
name,
delegate: prisma[delegateKey as keyof typeof prisma] as unknown as Delegate,
}))
let mongod: MongoMemoryServer | undefined
beforeAll(async () => {
const mongoUrl = new URL(process.env.MONGO_URL || '')
/**
* This patches prismock delegates to raise corresponding error
* in case of entity not found exception
*/
models.forEach(({ name, delegate }) => {
const originalFindUniqueOrThrow = delegate.findUniqueOrThrow
delegate.findUniqueOrThrow = async (
...args: Parameters<Delegate['findUniqueOrThrow']>
) => {
try {
return await originalFindUniqueOrThrow.apply(delegate, args)
} catch {
throw new PrismaClientKnownRequestError(`No ${name} found`, {
code: 'P2025',
clientVersion,
})
}
}
const originalFindFirstOrThrow = delegate.findFirstOrThrow
delegate.findFirstOrThrow = async (
...args: Parameters<Delegate['findFirstOrThrow']>
) => {
try {
return await originalFindFirstOrThrow.apply(delegate, args)
} catch {
throw new PrismaClientKnownRequestError(`No ${name} found`, {
code: 'P2025',
clientVersion,
})
}
}
const originalUpdate = delegate.update
delegate.update = async (...args: Parameters<Delegate['update']>) => {
const updated = await originalUpdate.apply(delegate, args)
if (!updated) {
throw new PrismaClientKnownRequestError(`No ${name} found`, {
code: 'P2025',
clientVersion,
meta: {
cause: 'Record to update not found.',
modelName: name,
},
})
}
return updated
}
const originalDelete = delegate.delete
delegate.delete = async (...args: Parameters<Delegate['delete']>) => {
try {
return await originalDelete.apply(delegate, args)
} catch {
throw new PrismaClientKnownRequestError(`No ${name} found`, {
code: 'P2025',
clientVersion,
meta: {
cause: 'Record to delete does not exist.',
modelName: name,
},
})
}
}
})
mongod = await MongoMemoryServer.create({
instance: {
port: +mongoUrl.port,
},
binary: {
// version: '4.0.3', // Should be activated
},
})
await connect()
})
afterAll(async () => {
await mongoose.disconnect()
await mongod?.stop()
})
beforeEach(() => nock.cleanAll())
afterEach(async () => {
expect(nock.isDone()).toBeTruthy()
await Promise.all(
models.map(async ({ delegate, name }) => {
try {
expect(await delegate.count({})).toBe(0)
} catch {
console.warn(
`${name} resources found after the test, please clean database after each test to avoid flaky tests`
)
}
})
)
})