我是 Nest js 的新手,并且不打算做一些测试。 我有一个房间控制器:
@Controller('rooms')
export class RoomController {
constructor(private readonly roomService: RoomService) {}
@Get()
async findAll(): Promise<ReadRoomDto[]> {
return await this.roomService.findAll();
}
}
还有客房服务
@Injectable()
export class RoomService {
constructor(
@InjectModel(Room.name) private readonly roomModel: RoomModel,
) {}
async findAll():Promise<ReadRoomDto[]> {
return await this.roomModel.find();
}
}
房间模型的形状如下:
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Model, Types } from 'mongoose';
import { Building } from 'src/modules/building/models/building.model';
import { Floor } from 'src/modules/floor/entities/floor.entity';
import { Organization } from 'src/modules/organization/models/organization.model';
import { Property } from 'src/modules/property/models/property.model';
interface RoomAttrs {
name: string;
floor?: string;
building?: string;
organization?: string;
properties?: string[];
}
export interface RoomModel extends Model<Room> {
build(attrs: RoomAttrs): Room;
}
@Schema()
export class Room extends Document {
@Prop()
name: String;
@Prop({ type: String, required: false, ref: Floor.name })
floor: String;
@Prop({ type: String, required: false, ref: Building.name })
building: String;
@Prop({ type: String, required: false, ref: Organization.name })
organization: String;
@Prop([{ type: String, required: false, ref: Property.name }])
properties: String[];
}
export const RoomSchema = SchemaFactory.createForClass(Room);
RoomSchema.set('toJSON', {
transform: (doc, ret) => {
ret.id = doc._id;
delete ret._id;
},
});
RoomSchema.statics.build = function (attrs: RoomAttrs) {
return new this(attrs);
};
当我在房间控制器上进行一些测试时:
import { Test, TestingModule } from '@nestjs/testing';
import { RoomController } from '../controllers/room.controller';
import { RoomStub } from './stubs/room.stub';
import { RoomService } from '../services/room.service';
const mockRoomService = {
findAll: jest.fn().mockResolvedValue([RoomStub()]),
};
describe('RoomController', () => {
let roomController: RoomController;
//let roomService :RoomService
beforeAll(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [RoomController],
providers: [{provide:RoomService,useValue:mockRoomService}],
}).compile();
roomController = module.get<RoomController>(RoomController);
//roomService = module.get<RoomService>(RoomService)
});
it('should be defined', () => {
expect(roomController).toBeDefined();
});
});
我总是收到错误:
Cannot find module 'src/modules/building/models/building.model' from 'modules/room/models/room.model.ts'
看来控制器没有使用模拟的服务,而是使用原始的客房服务。
问题是什么,因为我使用了创建服务模拟的所有方法来避免外部依赖项注入。
我用模拟和原始注入尝试了每种注入方法,但我总是得到一种使用原始服务的方式
Jest不明白如何解决绝对导入(
src/modules/building/models/building.model
)。您需要添加 moduleNameMapper jest 配置,以便它知道如何相对于 Jest is意识到的
src/*
来解析 rootDir
。通常是这样的
{
...
"moduleNameMapper": {
"^src/(.*)$": ["<rootDir>/$1"]
}
}
就是您要找的东西