我似乎无法在我的NestJS应用中找到此测试。按照用于连接NestJS & MongoDB的文档进行操作,我们在尝试运行createMember
规范时收到以下屏幕截图中的错误。我也在下面添加了服务及其各自的规范。公共仓库是https://github.com/alobban/zeta-nestjs/tree/mongo/src/member。
非常感谢您的帮助。
import { Model } from 'mongoose';
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Member } from './member.interface';
import { CreateMemberDto } from './dto/create-member-dto';
@Injectable()
export class MembersService {
members = [
{ firstName: 'Jake', lastName: 'Miller', lineName: 'State Farm' },
];
constructor(@InjectModel('Member') private readonly memberModel: Model<Member>) {}
async getMembers(): Promise<Member[]> {
return await this.memberModel.find().exec();
}
async createMember(createMemberDto: CreateMemberDto): Promise<Member> {
const createdMember = new this.memberModel(createMemberDto);
return await createdMember.save();
}
}
import { Test } from '@nestjs/testing';
import { MongooseModule, getModelToken } from '@nestjs/mongoose';
import { MembersService } from './members.service';
const members = [
{ firstName: 'Jake', lastName: 'Miller', lineName: 'State Farm' },
];
describe('MembersService', () => {
let membersService;
beforeEach(async () => {
const module = await Test.createTestingModule({
providers: [
MembersService,
{
provide: getModelToken('Member'),
useValue: {
find: jest.fn().mockReturnThis(),
exec: jest.fn().mockResolvedValue(members),
},
},
],
}).compile();
membersService = await module.get<MembersService>(MembersService);
});
describe('getMembers', () => {
it('calls getMembers and returns an array of Members', () => {
expect(membersService.getMembers()).resolves.toEqual(members);
});
});
describe('createMember', () => {
it('calls membersService.createMember and returns result', async () => {
const save = jest.fn().mockResolvedValue(true);
expect(save).not.toHaveBeenCalled();
const result = await membersService.createMember('newMember');
expect(save).toHaveBeenCalled();
});
});
});