在 Jest 的 beforeEach 中创建文档 nest.js

Create a document in beforeEach on Jest nest.js

我正在使用内存猫鼬数据库创建我的单元测试,我想在测试前创建一个文档。 我的界面是:

export interface IUsers {
  readonly name: string;
  readonly username: string;
  readonly email: string;
  readonly password: string;
}

我的 beforeEach 是:

 import { MongooseModule } from "@nestjs/mongoose";
 import { Test, TestingModule } from "@nestjs/testing";
 import { closeInMongodConnection, rootMongooseTestModule } from '../test-utils/mongo/MongooseTestModule';
 import { User, UserSchema } from "./schemas/users.schema";
 import { UsersService } from "./users.service";

describe("UsersService", () => {
    let service: UsersService;
      let testingModule: TestingModule;
      let userModel: Model<User>;
    
      
      beforeEach(async () => {
        const module: TestingModule = await Test.createTestingModule({
          imports: [
            rootMongooseTestModule(),
            MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]),
          ],
          providers: [UsersService],
        }).compile();
    
        service = module.get<UsersService>(UsersService);
    
        //create user    
        userModel = testingModule.get<Model<User>>(
          'UserModel',
        );
      });

我在测试期间遇到错误 TypeError: Cannot read pro perties of undefined (reading 'get')。我尝试使用 let userModel: Model<IUsers>; 但我得到了同样的错误。

使用 testingModulemodule

您声明了 testingModule 但从未初始化。

let testingModule: TestingModule; 这部分是未定义的,除非给它赋值。

这样试试

describe('UsersService', () => {
  let testingModule: TestingModule;
  let userModel: Model<User>;
  let userService: UserService;

  beforeEach(async () => {
    testingModule = await Test.createTestingModule({
      imports: [
        rootMongooseTestModule, 
        MongooseModule.forFeature([{ name: User.name, schema: UserSchema }])],
      providers: [UsersService],
    }).compile();

    userService = testingModule.get<UsersService>(UsersService);
    userModel = testingModule.get<Model<User>>('UserModel');
  // await userModel.create(...) or whatever methods you have
  });
});