|
| 1 | +import { Test, TestingModule } from '@nestjs/testing'; |
| 2 | +import { CatsController } from './cats.controller'; |
| 3 | +import { CreateCatDto } from './dto/create-cat.dto'; |
| 4 | +import { CatsService } from './cats.service'; |
| 5 | + |
| 6 | +describe('CatsController', () => { |
| 7 | + let controller: CatsController; |
| 8 | + let service: CatsService; |
| 9 | + |
| 10 | + beforeEach(async () => { |
| 11 | + const module: TestingModule = await Test.createTestingModule({ |
| 12 | + controllers: [CatsController], |
| 13 | + providers: [ |
| 14 | + { |
| 15 | + provide: CatsService, |
| 16 | + useValue: { |
| 17 | + findAll: jest.fn().mockResolvedValue([ |
| 18 | + { |
| 19 | + name: 'Cat #1', |
| 20 | + breed: 'Bread #1', |
| 21 | + age: 4, |
| 22 | + }, |
| 23 | + { |
| 24 | + name: 'Cat #2', |
| 25 | + breed: 'Breed #2', |
| 26 | + age: 3, |
| 27 | + }, |
| 28 | + { |
| 29 | + name: 'Cat #3', |
| 30 | + breed: 'Breed #3', |
| 31 | + age: 2, |
| 32 | + }, |
| 33 | + ]), |
| 34 | + create: jest |
| 35 | + .fn() |
| 36 | + .mockImplementation((createCatDto: CreateCatDto) => |
| 37 | + Promise.resolve({ _id: '1', ...createCatDto }), |
| 38 | + ), |
| 39 | + }, |
| 40 | + }, |
| 41 | + ], |
| 42 | + }).compile(); |
| 43 | + |
| 44 | + controller = module.get(CatsController); |
| 45 | + service = module.get(CatsService); |
| 46 | + }); |
| 47 | + |
| 48 | + it('should be defined', () => { |
| 49 | + expect(controller).toBeDefined(); |
| 50 | + }); |
| 51 | + |
| 52 | + describe('create()', () => { |
| 53 | + it('should create a new cat', async () => { |
| 54 | + const createCatDto: CreateCatDto = { |
| 55 | + name: 'Cat #1', |
| 56 | + breed: 'Breed #1', |
| 57 | + age: 4, |
| 58 | + }; |
| 59 | + |
| 60 | + expect(controller.create(createCatDto)).resolves.toEqual({ |
| 61 | + _id: '1', |
| 62 | + ...createCatDto, |
| 63 | + }); |
| 64 | + }); |
| 65 | + }); |
| 66 | + |
| 67 | + describe('findAll()', () => { |
| 68 | + it('should get an array of cats', () => { |
| 69 | + expect(controller.findAll()).resolves.toEqual([ |
| 70 | + { |
| 71 | + name: 'Cat #1', |
| 72 | + breed: 'Bread #1', |
| 73 | + age: 4, |
| 74 | + }, |
| 75 | + { |
| 76 | + name: 'Cat #2', |
| 77 | + breed: 'Breed #2', |
| 78 | + age: 3, |
| 79 | + }, |
| 80 | + { |
| 81 | + name: 'Cat #3', |
| 82 | + breed: 'Breed #3', |
| 83 | + age: 2, |
| 84 | + }, |
| 85 | + ]); |
| 86 | + }); |
| 87 | + }); |
| 88 | +}); |
0 commit comments