I have a nestjs service that uses mongoose. In a function I wish to test it creates a new model, but I could not find a way to mock that.
I have the following service
@Injectable()
export class ProjectService {
constructor(
@InjectModel("Project") private projectModel: Model<ProjectDocument>,
) {}
public dto2ProjectModel(dto: ProjectDto) {
return new this.projectModel({
_id: dto.id? Types.ObjectId(dto.id) : Types.ObjectId(),
name: dto.name.toUpperCase()
});
}
}
And I created the test following the documentation like so:
describe('ProjectService tests', () => {
let projectService: ProjectService;
beforeEach(async () => {
const moduleRef = await Test.createTestingModule({
providers: [
ProjectService,
{
provide: getModelToken("Project"),
useValue: {
find: jest.fn(),
findById: jest.fn()
}
}
]
}).compile();
projectService = moduleRef.get<ProjectService>(ProjectService);
});
describe('dto2ProjectModel', () => {
it('should return a project with the uppercase name', async () => {
const projectDto: ProjectDto = new ProjectDto();
projectDto.id = '5a2539b41c574006c46f1a09';
projectDto.name = 'someName';
expect(await projectService.dto2ProjectModel(projectDto).name).toEqual('SOMENAME');
});
});
});
I tried doing it by example on nestjs documentation and mocking model methods like find is fine, but the new this.projectModel({}) does not work.
Any ideas are greatly appreciated!