Currently undergoing unit testing for my NestJS Service with an entity named 'User'. I have created a simple Service to interact with a MS SQL server, setting up GET and POST endpoints in the Controller.
One of the service methods I am focusing on mocking is the deleteV2
function, as shown below:
// service file
import { Injectable } from '@nestjs/common';
import { InjectConnection, InjectEntityManager, InjectRepository } from '@nestjs/typeorm';
import { Connection, createConnection, EntityManager, getConnection, getManager, getRepository, Repository } from "typeorm";
import {User} from '../entities/user.entity';
@Injectable()
export class ServiceName {
constructor(@InjectRepository(User) private usersRepository: Repository<User>,
@InjectConnection() private connection: Connection,
@InjectEntityManager() private manager: EntityManager
) {}
async delete(id: number): Promise<any> {
return await this.manager.delete(User, id);
}
async deleteV2(id: number): Promise<any> {
return await getManager().delete(User, id);
}
Importing EntityManager
and injecting a manager: EntityManager
into my service is for practicing different methods as a new intern working with NestJS. The unique use of defining both delete
and deleteV2
methods serves a purpose in unit testing with varied approaches. Repository, Connection, and EntityManager injection further contribute to this practice.
In my spec.ts unit testing file for the service, I have:
// unit testing file for the service
type MockType<T> = {
[P in keyof T]?: jest.Mock<{}>;
};
describe('service tests', () => {
const mockManagerFactory = jest.fn(() => ({
delete: jest.fn().mockReturnValue(undefined),
}))
let service: ServiceName;
let mockManager: MockType<EntityManager>;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
ServiceName,
{
provide: getEntityManagerToken(),
useFactory: mockManagerFactory,
},
],
}).compile();
service = module.get<ServiceName>(ServiceName);
mockManager = module.get(getEntityManagerToken());
});
})
Within the same spec.ts file, multiple tests are defined. The one concerning deleteV2
is causing issues. The error message encountered is:
● service tests › Service Functions › second test
ConnectionNotFoundError: Connection "default" was not found.
at new ConnectionNotFoundError (error/ConnectionNotFoundError.ts:8:9)
at ConnectionManager.Object.<anonymous>.ConnectionManager.get (connection/ConnectionManager.ts:40:19)
at Object.getManager (index.ts:260:35)
Seeking advice on how to resolve this error, specifically related to handling the imported getManager
method in comparison to the injected manager
within the service.