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



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

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

和我以前的每个都是:

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
});
});

相关内容

最新更新