-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostService.test.ts
288 lines (229 loc) · 8.96 KB
/
PostService.test.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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
import {
ForbiddenException,
InternalServerErrorException,
NotFoundException,
} from '@nestjs/common';
import { getConnectionToken, getModelToken } from '@nestjs/mongoose';
import { Test, TestingModule } from '@nestjs/testing';
import { Connection as MongooseConnection, Model } from 'mongoose';
import { Comment, CommentDocument } from '#server/comment/schemas/CommentSchema.js';
import { PostService } from '#server/post/PostService.js';
import { Post, PostDocument } from '#server/post/schemas/PostSchema.js';
import { mockCommentModel } from '#test/server/comment/mocks/index.js';
import { mockMongoConnection } from '#test/server/mocks/index.js';
import {
mockMongoPost,
mockMongoPosts,
mockPostModel,
mockUpdatedMongoPost,
mockUpsertPost,
} from '#test/server/post/mocks/index.js';
const postId = '1';
const userId = '1';
describe('PostService', () => {
let commentModel: Model<CommentDocument>;
let postModel: Model<PostDocument>;
let connection: MongooseConnection;
let postService: PostService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
PostService,
{
provide: getModelToken(Post.name),
useValue: mockPostModel,
},
{
provide: getModelToken(Comment.name),
useValue: mockCommentModel,
},
{
provide: getConnectionToken(),
useValue: mockMongoConnection,
},
],
}).compile();
commentModel = module.get<Model<CommentDocument>>(getModelToken(Comment.name));
postModel = module.get<Model<PostDocument>>(getModelToken(Post.name));
connection = module.get<MongooseConnection>(getConnectionToken());
postService = module.get<PostService>(PostService);
});
afterEach(() => {
vi.clearAllMocks();
});
describe('getAll', () => {
it('should get all posts using post model', async () => {
await postService.getAll();
expect(postModel.find).toHaveBeenCalled();
});
it('should return all posts', async () => {
expect(await postService.getAll()).toEqual(mockMongoPosts);
});
});
describe('getById', () => {
it('should get post by id using post model', async () => {
await postService.getById(postId);
expect(postModel.findById).toHaveBeenCalledWith(postId);
});
describe('post exists', () => {
it('should return post', async () => {
expect(await postService.getById(postId)).toEqual(mockMongoPost);
});
});
describe('post does not exist', () => {
it('should throw not found exception', async () => {
vi.spyOn(postModel, 'findById').mockResolvedValueOnce(null);
await expect(postService.getById(postId)).rejects.toThrowError(NotFoundException);
});
});
});
describe('create', () => {
it('should create post using post model', async () => {
await postService.create(mockUpsertPost, userId);
expect(postModel.create).toHaveBeenCalledWith({ ...mockUpsertPost, author: userId });
});
describe('post model success', () => {
it('should return created post', async () => {
expect(await postService.create(mockUpsertPost, userId)).toEqual(mockMongoPost);
});
});
});
describe('update', () => {
it('should get post by id', async () => {
vi.spyOn(postService, 'getById').mockResolvedValueOnce(mockMongoPost);
await postService.update(postId, mockUpsertPost, userId);
expect(postService.getById).toHaveBeenCalledWith(postId);
});
it('should throw forbidden exception if author id does not match user id', async () => {
vi.spyOn(postService, 'getById').mockResolvedValueOnce(<PostDocument>{ author: { id: '2' } });
await expect(postService.update(postId, mockUpsertPost, userId)).rejects.toThrowError(
ForbiddenException,
);
});
it('should update post using post model', async () => {
await postService.update(postId, mockUpsertPost, userId);
expect(postModel.findByIdAndUpdate).toHaveBeenCalledWith(postId, mockUpsertPost, {
new: true,
});
});
describe('post exists', () => {
it('should return updated post', async () => {
expect(await postService.update(postId, mockUpsertPost, userId)).toEqual(
mockUpdatedMongoPost,
);
});
});
describe('post does not exist', () => {
it('should throw not found exception', async () => {
vi.spyOn(postModel, 'findByIdAndUpdate').mockResolvedValueOnce(null);
await expect(postService.update(postId, mockUpsertPost, userId)).rejects.toThrowError(
NotFoundException,
);
});
});
});
describe('delete', () => {
it('should start session', async () => {
vi.spyOn(connection, 'startSession');
await postService.delete(postId, userId);
expect(connection.startSession).toHaveBeenCalledOnce();
});
it('should get post by id', async () => {
vi.spyOn(postService, 'getById');
await postService.delete(postId, userId);
expect(postService.getById).toHaveBeenCalledWith(postId);
});
describe('author id does not match user id', () => {
it('should abort transaction', async () => {
const session = await connection.startSession();
vi.spyOn(postService, 'getById').mockResolvedValueOnce(<PostDocument>{
author: { id: '2' },
});
vi.spyOn(connection, 'startSession').mockImplementationOnce(async () => session);
try {
await postService.delete(postId, userId);
} catch {}
expect(session.abortTransaction).toHaveBeenCalledOnce();
});
it('should throw forbidden exception', async () => {
vi.spyOn(postService, 'getById').mockResolvedValueOnce(<PostDocument>{
author: { id: '2' },
});
await expect(postService.delete(postId, userId)).rejects.toThrowError(ForbiddenException);
});
});
it('should delete post using post model', async () => {
await postService.delete(postId, userId);
expect(postModel.deleteOne).toHaveBeenCalledWith({ _id: postId });
});
it('should delete post comments using comment model', async () => {
await postService.delete(postId, userId);
expect(commentModel.deleteMany).toHaveBeenCalledWith({
_id: {
$in: mockMongoPost.comments.map(({ id }) => id),
},
});
});
it('should commit transaction', async () => {
const session = await connection.startSession();
vi.spyOn(connection, 'startSession').mockImplementationOnce(async () => session);
await postService.delete(postId, userId);
expect(session.commitTransaction).toHaveBeenCalledOnce();
});
describe('deleted posts count is 0', () => {
it('should abort transaction', async () => {
const session = await connection.startSession();
vi.spyOn(postModel, 'deleteOne').mockResolvedValueOnce({
deletedCount: 0,
acknowledged: true,
});
vi.spyOn(connection, 'startSession').mockImplementationOnce(async () => session);
try {
await postService.delete(postId, userId);
} catch {}
expect(session.abortTransaction).toHaveBeenCalledOnce();
});
it('should throw internal server error', async () => {
vi.spyOn(postModel, 'deleteOne').mockResolvedValueOnce({
deletedCount: 0,
acknowledged: true,
});
await expect(postService.delete(postId, userId)).rejects.toThrowError(
InternalServerErrorException,
);
});
});
describe('deleted comments count is lower that post comments count', () => {
it('should abort transaction', async () => {
const session = await connection.startSession();
vi.spyOn(commentModel, 'deleteMany').mockResolvedValueOnce({
deletedCount: mockMongoPost.comments.length - 1,
acknowledged: true,
});
vi.spyOn(connection, 'startSession').mockImplementationOnce(async () => session);
try {
await postService.delete(postId, userId);
} catch {}
expect(session.abortTransaction).toHaveBeenCalledOnce();
});
it('should throw internal server error', async () => {
vi.spyOn(commentModel, 'deleteMany').mockResolvedValueOnce({
deletedCount: mockMongoPost.comments.length - 1,
acknowledged: true,
});
await expect(postService.delete(postId, userId)).rejects.toThrowError(
InternalServerErrorException,
);
});
});
it('should return undefined if post was successfully deleted', async () => {
expect(await postService.delete(postId, userId)).toEqual(undefined);
});
it('should end session', async () => {
const session = await connection.startSession();
vi.spyOn(connection, 'startSession').mockImplementationOnce(async () => session);
await postService.delete(postId, userId);
expect(session.endSession).toHaveBeenCalledOnce();
});
});
});