import { Test, TestingModule } from '@nestjs/testing';
import { TransferService } from './transfer.service'; // Assuming the service is named TransferService
import { VendorService } from '../vendor/vendor.service'; // Assuming VendorService path
import { LocationService } from '../location/location.service'; // Assuming LocationService path
import { getRepositoryToken } from '@nestjs/typeorm';
import { Transfer } from './entities/transfer.entity'; // Assuming Transfer entity path
import { Repository } from 'typeorm';
import { CreateTransferDto } from './dto/create-transfer.dto'; // Assuming DTO path
import { TransferReturnDto } from './dto/transfer-return.dto'; // Assuming DTO path
import { BadRequestException, NotFoundException } from '@nestjs/common';
import { ValidatorHelper } from '../../common/helpers/validator.helper'; // Assuming ValidatorHelper path
// Mock the ValidatorHelper explicitly
jest.mock('../../common/helpers/validator.helper');
const mockedValidatorHelper = ValidatorHelper as jest.Mock;
// Mock Vendor and Location interfaces/types if they are complex, otherwise simple objects suffice
interface MockVendor {
ID: number;
name: string;
}
interface MockLocation {
ID: number;
name: string;
}
describe('TransferService', () => {
let service: TransferService;
let vendorService: jest.Mocked<VendorService>;
let locationService: jest.Mocked<LocationService>;
let repo: jest.Mocked<Repository<Transfer>>;
beforeEach(async () => {
// Reset mocks before each test
jest.clearAllMocks();
const module: TestingModule = await Test.createTestingModule({
providers: [
TransferService,
{
provide: VendorService,
useValue: {
FindOneById: jest.fn(),
},
},
{
provide: LocationService,
useValue: {
FindOneById: jest.fn(),
},
},
{
provide: getRepositoryToken(Transfer),
useValue: {
create: jest.fn(),
save: jest.fn(), // Use save for entity instances
insert: jest.fn(), // Or insert if creating from plain object
findOne: jest.fn(), // For the FindOneById implementation in the service
},
},
],
}).compile();
service = module.get<TransferService>(TransferService);
vendorService = module.get(VendorService);
locationService = module.get(LocationService);
repo = module.get(getRepositoryToken(Transfer));
// Implement FindOneById for the service using the mocked repo
// This assumes TransferService has a FindOneById method that uses this.repo.findOne
// Mock the repo's findOne method directly for the service's FindOneById
(service.FindOneById as jest.Mock) = jest.fn().mockImplementation(async (id: number) => {
const found = await repo.findOne({ where: { ID: id } } as any); // Type assertion needed for mock
if (!found) {
throw new NotFoundException(`Transfer with ID ${id} not found`);
}
return found;
});
});
it('should be defined', () => {
expect(service).toBeDefined();
});
describe('Create', () => {
const mockUserId = 1;
const mockLocationFromId = 10;
const mockLocationToId = 20;
const mockShipmentId = 100;
// Mock successful service responses
const mockShipment: MockVendor = { ID: mockShipmentId, name: 'Test Shipment' };
const mockLocationFrom: MockLocation = { ID: mockLocationFromId, name: 'Warehouse A' };
const mockLocationTo: MockLocation = { ID: mockLocationToId, name: 'Warehouse B' };
// Mock Transfer entity and DTO
const mockCreateDto: CreateTransferDto = {
Date: new Date(),
LocationFromId: mockLocationFromId,
LocationToId: mockLocationToId,
ShipmentId: mockShipmentId,
// other required DTO fields...
};
const mockTransferEntity = {
ID: expect.any(Number), // ID is generated by DB typically
...mockCreateDto,
UserId: mockUserId,
// Add any other fields Transfer entity might have
}
// Mock the return value from repo.save or repo.create + repo.insert
// Use save mock for cleaner test
const savedTransfer = { ...mockTransferEntity, ID: 1 }; // Assume ID 1 is assigned
it('should successfully create a transfer', async () => {
// Arrange
mockedValidatorHelper.mockResolvedValue(undefined); // Mock successful validation
vendorService.FindOneById.mockResolvedValue(mockShipment);
locationService.FindOneById.mockResolvedValueOnce(mockLocationFrom).mockResolvedValueOnce(mockLocationTo);
repo.create.mockReturnValue(mockTransferEntity as Transfer); // Return the entity instance
repo.save.mockResolvedValue(savedTransfer as Transfer); // Mock successful save
// Act
const result = await service.Create(mockCreateDto, mockUserId);
// Assert
expect(mockedValidatorHelper).toHaveBeenCalledWith(mockCreateDto, CreateTransferDto, true);
expect(vendorService.FindOneById).toHaveBeenCalledWith(mockShipmentId);
expect(locationService.FindOneById).toHaveBeenCalledWith(mockLocationFromId);
expect(locationService.FindOneById).toHaveBeenCalledWith(mockLocationToId);
expect(repo.create).toHaveBeenCalledWith(expect.objectContaining({
Date: mockCreateDto.Date,
UserId: mockUserId,
ShipmentId: mockShipmentId,
LocationFromId: mockLocationFromId,
LocationToId: mockLocationToId,
}));
expect(repo.save).toHaveBeenCalledTimes(1); // Use save instead of create+insert for entity instance
expect(service.FindOneById).toHaveBeenCalledWith(savedTransfer.ID); // Check if FindOneById was called
expect(result).toEqual(savedTransfer); // Check if the correct result is returned
});
it('should throw BadRequestException if LocationFromId and LocationToId are the same', async () => {
// Arrange
const dtoWithSameLocations: CreateTransferDto = {
...mockCreateDto,
LocationFromId: 50,
LocationToId: 50,
};
// Act & Assert
await expect(service.Create(dtoWithSameLocations, mockUserId)).rejects.toThrow(
new BadRequestException('Location From and Location To cannot be same.'),
);
// Ensure other service calls are not made
expect(mockedValidatorHelper).toHaveBeenCalledTimes(1); // Validator should still run
expect(vendorService.FindOneById).not.toHaveBeenCalled();
expect(locationService.FindOneById).not.toHaveBeenCalled();
expect(repo.create).not.toHaveBeenCalled();
expect(repo.save).not.toHaveBeenCalled();
});
it('should throw NotFoundException if ShipmentId does not exist', async () => {
// Arrange
mockedValidatorHelper.mockResolvedValue(undefined);
vendorService.FindOneById.mockResolvedValue(null); // Simulate shipment not found
// Act & Assert
await expect(service.Create(mockCreateDto, mockUserId)).rejects.toThrow(
new NotFoundException(`Shipment with ID ${mockShipmentId} not found.`),
);
// Ensure only relevant calls were made
expect(mockedValidatorHelper).toHaveBeenCalledTimes(1);
expect(vendorService.FindOneById).toHaveBeenCalledWith(mockShipmentId);
expect(locationService.FindOneById).not.toHaveBeenCalled();
expect(repo.create).not.toHaveBeenCalled();
expect(repo.save).not.toHaveBeenCalled();
});
it('should throw NotFoundException if LocationFromId does not exist', async () => {
// Arrange
mockedValidatorHelper.mockResolvedValue(undefined);
vendorService.FindOneById.mockResolvedValue(mockShipment);
locationService.FindOneById.mockResolvedValueOnce(null); // Simulate locationFrom not found
// Act & Assert
await expect(service.Create(mockCreateDto, mockUserId)).rejects.toThrow(
new NotFoundException(`Location with ID ${mockLocationFromId} not found.`),
);
// Ensure relevant calls were made
expect(mockedValidatorHelper).toHaveBeenCalledTimes(1);
expect(vendorService.FindOneById).toHaveBeenCalledWith(mockShipmentId);
expect(locationService.FindOneById).toHaveBeenCalledWith(mockLocationFromId);
expect(locationService.FindOneById).toHaveBeenCalledTimes(1); // Only called once
expect(repo.create).not.toHaveBeenCalled();
expect(repo.save).not.toHaveBeenCalled();
});
it('should throw NotFoundException if LocationToId does not exist', async () => {
// Arrange
mockedValidatorHelper.mockResolvedValue(undefined);
vendorService.FindOneById.mockResolvedValue(mockShipment);
locationService.FindOneById.mockResolvedValueOnce(mockLocationFrom).mockResolvedValueOnce(null); // Simulate locationTo not found
// Act & Assert
await expect(service.Create(mockCreateDto, mockUserId)).rejects.toThrow(
new NotFoundException(`Location with ID ${mockLocationToId} not found.`),
);
// Ensure relevant calls were made
expect(mockedValidatorHelper).toHaveBeenCalledTimes(1);
expect(vendorService.FindOneById).toHaveBeenCalledWith(mockShipmentId);
expect(locationService.FindOneById).toHaveBeenCalledWith(mockLocationFromId);
expect(locationService.FindOneById).toHaveBeenCalledWith(mockLocationToId);
expect(locationService.FindOneById).toHaveBeenCalledTimes(2); // Called twice
expect(repo.create).not.toHaveBeenCalled();
expect(repo.save).not.toHaveBeenCalled();
});
it('should throw an error if the repository save operation fails', async () => {
// Arrange
const repoError = new Error('Database constraint violation');
mockedValidatorHelper.mockResolvedValue(undefined);
vendorService.FindOneById.mockResolvedValue(mockShipment);
locationService.FindOneById.mockResolvedValueOnce(mockLocationFrom).mockResolvedValueOnce(mockLocationTo);
repo.create.mockReturnValue(mockTransferEntity as Transfer);
repo.save.mockRejectedValue(repoError); // Simulate repository save failure
// Act & Assert
await expect(service.Create(mockCreateDto, mockUserId)).rejects.toThrow(repoError);
// Ensure calls up to save were made
expect(mockedValidatorHelper).toHaveBeenCalledTimes(1);
expect(vendorService.FindOneById).toHaveBeenCalledWith(mockShipmentId);
expect(locationService.FindOneById).toHaveBeenCalledWith(mockLocationFromId);
expect(locationService.FindOneById).toHaveBeenCalledWith(mockLocationToId);
expect(repo.create).toHaveBeenCalledTimes(1);
expect(repo.save).toHaveBeenCalledTimes(1);
expect(service.FindOneById).not.toHaveBeenCalled(); // FindOneById should not be called if save fails
});
it('should throw an error if the FindOneById call within Create fails', async () => {
// Arrange
const findOneError = new Error('Error retrieving created transfer');
mockedValidatorHelper.mockResolvedValue(undefined);
vendorService.FindOneById.mockResolvedValue(mockShipment);
locationService.FindOneById.mockResolvedValueOnce(mockLocationFrom).mockResolvedValueOnce(mockLocationTo);
repo.create.mockReturnValue(mockTransferEntity as Transfer);
repo.save.mockResolvedValue(savedTransfer as Transfer);
// Explicitly mock the service's FindOneById to reject
(service.FindOneById as jest.Mock).mockRejectedValueOnce(findOneError);
// Act & Assert
await expect(service.Create(mockCreateDto, mockUserId)).rejects.toThrow(findOneError);
// Ensure all calls up to FindOneById were made
expect(mockedValidatorHelper).toHaveBeenCalledTimes(1);
expect(vendorService.FindOneById).toHaveBeenCalledWith(mockShipmentId);
expect(locationService.FindOneById).toHaveBeenCalledWith(mockLocationFromId);
expect(locationService.FindOneById).toHaveBeenCalledWith(mockLocationToId);
expect(repo.create).toHaveBeenCalledTimes(1);
expect(repo.save).toHaveBeenCalledTimes(1);
expect(service.FindOneById).toHaveBeenCalledWith(savedTransfer.ID); // Ensure it was attempted
});
});
});
// Placeholder for the actual TransferService class if needed for context,
// but the tests above use dependency injection mocks effectively.
// Ensure the service class itself handles the dependencies correctly.
/*
// Example structure of TransferService (for context of tests)
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Transfer } from './entities/transfer.entity';
import { CreateTransferDto } from './dto/create-transfer.dto';
import { TransferReturnDto } from './dto/transfer-return.dto';
import { VendorService } from '../vendor/vendor.service';
import { LocationService } from '../location/location.service';
import { BadRequestException, NotFoundException } from '@nestjs/common';
import { ValidatorHelper } from '../../common/helpers/validator.helper';
@Injectable()
export class TransferService {
constructor(
@InjectRepository(Transfer)
private readonly repo: Repository<Transfer>,
private readonly vendorService: VendorService,
private readonly locationService: LocationService,
) {}
async Create(dto: CreateTransferDto, userId: number): Promise<TransferReturnDto> {
await ValidatorHelper(dto, CreateTransferDto, true);
if (dto.LocationFromId === dto.LocationToId) {
throw new BadRequestException('Location From and Location To cannot be same.');
}
const shipment = await this.vendorService.FindOneById(dto.ShipmentId);
if (!shipment) {
throw new NotFoundException(`Shipment with ID ${dto.ShipmentId} not found.`);
}
const locationFrom = await this.locationService.FindOneById(dto.LocationFromId);
if (!locationFrom) {
throw new NotFoundException(`Location with ID ${dto.LocationFromId} not found.`);
}
const locationTo = await this.locationService.FindOneById(dto.LocationToId);
if (!locationTo) {
throw new NotFoundException(`Location with ID ${dto.LocationToId} not found.`);
}
const transfer = this.repo.create({
Date: dto.Date,
UserId: userId,
ShipmentId: shipment.ID, // Use the validated ID
LocationFromId: locationFrom.ID, // Use the validated ID
LocationToId: locationTo.ID, // Use the validated ID
// Map other fields if necessary
});
const transferDb = await this.repo.save(transfer); // Use save for entity instances
// Assuming FindOneById fetches details and potentially maps to TransferReturnDto
return await this.FindOneById(transferDb.ID);
}
// Dummy FindOneById implementation for the service's internal use
// The test mocks this specific method call
async FindOneById(id: number): Promise<TransferReturnDto> {
const transfer = await this.repo.findOne({ where: { ID: id } } as any);
if (!transfer) {
throw new NotFoundException(`Transfer with ID ${id} not found`);
}
// Map to TransferReturnDto if necessary
return transfer as unknown as TransferReturnDto;
}
}
*/