forked from nestjs/nest
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcats.service.spec.ts
78 lines (70 loc) · 1.76 KB
/
cats.service.spec.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
import { Test, TestingModule } from '@nestjs/testing';
import { CatsService } from './cats.service';
import { Cat } from './interfaces/cat.interface';
import { Model } from 'mongoose';
const mockCat = {
name: 'Cat #1',
breed: 'Breed #1',
age: 4,
};
describe('CatService', () => {
let service: CatsService;
let model: Model<Cat>;
const catsArray = [
{
name: 'Cat #1',
breed: 'Breed #1',
age: 4,
},
{
name: 'Cat #2',
breed: 'Breed #2',
age: 2,
},
];
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
CatsService,
{
provide: 'CAT_MODEL',
useValue: {
new: jest.fn().mockResolvedValue(mockCat),
constructor: jest.fn().mockResolvedValue(mockCat),
find: jest.fn(),
create: jest.fn(),
save: jest.fn(),
exec: jest.fn(),
},
},
],
}).compile();
service = module.get(CatsService);
model = module.get<Model<Cat>>('CAT_MODEL');
});
it('should be defined', () => {
expect(service).toBeDefined();
});
it('should return all cats', async () => {
jest.spyOn(model, 'find').mockReturnValue({
exec: jest.fn().mockResolvedValueOnce(catsArray),
} as any);
const cats = await service.findAll();
expect(cats).toEqual(catsArray);
});
it('should insert a new cat', async () => {
jest.spyOn(model, 'create').mockImplementationOnce(() =>
Promise.resolve({
name: 'Cat #1',
breed: 'Breed #1',
age: 4,
}),
);
const newCat = await service.create({
name: 'Cat #1',
breed: 'Breed #1',
age: 4,
});
expect(newCat).toEqual(mockCat);
});
});