I am currently trying to execute my test file in NestJS. My goal is to connect to a test database and run my service with it. However, I am facing an issue where my service is undefined and the method service.findById is also undefined. How can I obtain an instance of the UserService in my test file?
user.service.ts
import { Injectable } from '@nestjs/common';
import { User } from './model/user.model';
import { InjectModel } from '@nestjs/sequelize';
@Injectable()
export class UserService {
constructor(
@InjectModel(User)
private userModel: typeof User,
) {}
async findById(id: number): Promise<User> {
return await this.userModel.findOne({
where: { id },
raw: true,
nest: true,
});
}
}
user.service.spec.ts
import { Test, TestingModule } from '@nestjs/testing';
import { UserService } from './user.service';
import { SequelizeModule } from '@nestjs/sequelize';
describe('UserService', () => {
let service: UserService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
imports: [
SequelizeModule.forRoot({
dialect: 'postgres',
host: 'localhost',
port: 5432,
username: 'postgres',
password: '@@@',
database: 'test',
}),
],
providers: [UserService],
}).compile();
service = module.get<UserService>(UserService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
it('should return id', async () => {
const user = await service.findById(1)
expect(user.id).toBeDefined();
});
});