forked from DogStark/petChain-Frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbehavior.service.spec.ts
More file actions
190 lines (154 loc) · 6.67 KB
/
Copy pathbehavior.service.spec.ts
File metadata and controls
190 lines (154 loc) · 6.67 KB
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
import { Test, TestingModule } from '@nestjs/testing';
import { BehaviorService } from './behavior.service';
import { getRepositoryToken } from '@nestjs/typeorm';
import { Behavior } from './entities/behavior.entity';
import { Repository } from 'typeorm';
import { BadRequestException, NotFoundException } from '@nestjs/common';
import { CreateBehaviorDto } from './dto/create-behavior.dto';
import { UpdateBehaviorDto } from './dto/update-behavior.dto';
describe('BehaviorService', () => {
let service: BehaviorService;
let repository: Repository<Behavior>;
// Mock Data
const mockBehavior = {
id: 'uuid-123',
petId: 'pet-456',
type: 'Aggression',
description: 'Barked at mailman',
severity: 3,
metrics: { intensity: 'medium', duration: 30 },
createdAt: new Date(),
updatedAt: new Date(),
};
const mockBehaviorRepository = {
create: jest.fn().mockImplementation((dto) => dto),
save: jest.fn().mockResolvedValue(mockBehavior),
find: jest.fn().mockResolvedValue([mockBehavior]),
findOne: jest.fn().mockResolvedValue(mockBehavior),
update: jest.fn().mockResolvedValue({ affected: 1 }),
delete: jest.fn().mockResolvedValue({ affected: 1 }),
};
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
BehaviorService,
{
provide: getRepositoryToken(Behavior),
useValue: mockBehaviorRepository,
},
],
}).compile();
service = module.get<BehaviorService>(BehaviorService);
repository = module.get<Repository<Behavior>>(getRepositoryToken(Behavior));
});
afterEach(() => {
jest.clearAllMocks();
});
it('should be defined', () => {
expect(service).toBeDefined();
});
describe('create', () => {
const createDto: CreateBehaviorDto = {
petId: 'pet-456',
type: 'Aggression',
description: 'Barked at mailman',
severity: 3,
metrics: { intensity: 'medium', duration: 30 },
};
it('should successfully create a behavior log', async () => {
const result = await service.create(createDto);
expect(repository.create).toHaveBeenCalledWith(createDto);
expect(repository.save).toHaveBeenCalled();
expect(result).toEqual(mockBehavior);
});
it('should throw BadRequestException if severity is out of bounds (Business Logic)', async () => {
const invalidDto = { ...createDto, severity: 11 }; // Assume 1-10 scale
// Mocking a service-level validation check
await expect(service.create(invalidDto)).rejects.toThrow(BadRequestException);
});
it('should throw BadRequestException if metrics are malformed', async () => {
const invalidDto = { ...createDto, metrics: null } as any;
await expect(service.create(invalidDto)).rejects.toThrow(BadRequestException);
});
});
describe('findAll and filtering', () => {
it('should return an array of behavior logs', async () => {
const result = await service.findAll();
expect(result).toEqual([mockBehavior]);
expect(repository.find).toHaveBeenCalled();
});
it('should apply filters correctly when provided', async () => {
const filters = { petId: 'pet-456', type: 'Aggression' };
await service.findAll(filters);
expect(repository.find).toHaveBeenCalledWith({
where: filters,
});
});
});
describe('findOne', () => {
it('should return a single behavior log', async () => {
const result = await service.findOne('uuid-123');
expect(result).toEqual(mockBehavior);
expect(repository.findOne).toHaveBeenCalledWith({ where: { id: 'uuid-123' } });
});
it('should throw NotFoundException if log does not exist', async () => {
jest.spyOn(repository, 'findOne').mockResolvedValueOnce(null);
await expect(service.findOne('invalid-id')).rejects.toThrow(NotFoundException);
});
});
describe('update', () => {
const updateDto: UpdateBehaviorDto = {
description: 'Updated description',
severity: 4,
};
it('should successfully update a behavior log', async () => {
const updatedResult = { ...mockBehavior, ...updateDto };
// Mock findOne twice: once for the initial existence check and once for the post-update return
jest.spyOn(service, 'findOne')
.mockResolvedValueOnce(mockBehavior as any)
.mockResolvedValueOnce(updatedResult as any);
const result = await service.update('uuid-123', updateDto);
expect(repository.update).toHaveBeenCalledWith('uuid-123', updateDto);
expect(result).toEqual(updatedResult);
});
it('should throw BadRequestException for invalid update metrics', async () => {
const invalidUpdate = { severity: -1 };
await expect(service.update('uuid-123', invalidUpdate)).rejects.toThrow(BadRequestException);
});
it('should throw NotFoundException if record to update is missing', async () => {
jest.spyOn(repository, 'findOne').mockResolvedValueOnce(null);
await expect(service.update('non-existent', updateDto)).rejects.toThrow(NotFoundException);
});
});
describe('remove', () => {
it('should successfully delete a behavior log', async () => {
// Mock existence check
jest.spyOn(repository, 'findOne').mockResolvedValueOnce(mockBehavior as any);
const result = await service.remove('uuid-123');
expect(repository.delete).toHaveBeenCalledWith('uuid-123');
expect(result).toEqual({ deleted: true });
});
it('should throw NotFoundException if trying to delete non-existent log', async () => {
jest.spyOn(repository, 'findOne').mockResolvedValueOnce(null);
await expect(service.remove('uuid-123')).rejects.toThrow(NotFoundException);
expect(repository.delete).not.toHaveBeenCalled();
});
});
describe('Workflow: Behavior Tracking Logic', () => {
it('should validate that a behavior log cannot be created without a valid pet reference', async () => {
const noPetDto = { type: 'Anxiety', severity: 1 } as CreateBehaviorDto;
await expect(service.create(noPetDto)).rejects.toThrow(BadRequestException);
});
it('should ensure timestamps are not manually overwritable during creation', async () => {
const maliciousDto = {
...mockBehavior,
createdAt: new Date('2000-01-01'), // Attempting to spoof history
} as any;
await service.create(maliciousDto);
// Check that repository.create was called but we rely on DB/Repository for actual timestamping
expect(repository.create).toHaveBeenCalled();
const callArgs = (repository.create as jest.Mock).mock.calls[0][0];
expect(callArgs.createdAt).toBeUndefined(); // Assuming DTO strips it or service ignores it
});
});
});