59 lines
1.8 KiB
TypeScript
59 lines
1.8 KiB
TypeScript
import { Test, TestingModule } from '@nestjs/testing';
|
|
import { ProductsController } from './products.controller';
|
|
import { ProductsService } from './products.service';
|
|
import { NotFoundException } from '@nestjs/common';
|
|
|
|
describe('ProductsController', () => {
|
|
let controller: ProductsController;
|
|
let service: ProductsService;
|
|
|
|
const mockProductsService = {
|
|
findAll: jest
|
|
.fn()
|
|
.mockResolvedValue([{ id: 'prod-id', name: 'Product 1' }]),
|
|
findOne: jest.fn(),
|
|
};
|
|
|
|
beforeEach(async () => {
|
|
const module: TestingModule = await Test.createTestingModule({
|
|
controllers: [ProductsController],
|
|
providers: [{ provide: ProductsService, useValue: mockProductsService }],
|
|
}).compile();
|
|
|
|
controller = module.get<ProductsController>(ProductsController);
|
|
service = module.get<ProductsService>(ProductsService);
|
|
});
|
|
|
|
afterEach(() => {
|
|
jest.clearAllMocks();
|
|
});
|
|
|
|
it('should be defined', () => {
|
|
expect(controller).toBeDefined();
|
|
});
|
|
|
|
it('should list products', async () => {
|
|
const query = { category: 'joints' };
|
|
const result = await controller.findAll(query);
|
|
expect(service.findAll).toHaveBeenCalledWith(query);
|
|
expect(result).toHaveLength(1);
|
|
});
|
|
|
|
describe('findOne', () => {
|
|
it('should throw NotFoundException if product not found', async () => {
|
|
mockProductsService.findOne.mockResolvedValue(null);
|
|
await expect(controller.findOne('invalid-id')).rejects.toThrow(
|
|
NotFoundException,
|
|
);
|
|
});
|
|
|
|
it('should return product details if found', async () => {
|
|
const prod = { id: 'prod-id', name: 'Product 1' };
|
|
mockProductsService.findOne.mockResolvedValue(prod);
|
|
const result = await controller.findOne('prod-id');
|
|
expect(service.findOne).toHaveBeenCalledWith('prod-id');
|
|
expect(result).toEqual(prod);
|
|
});
|
|
});
|
|
});
|