请确保索引[0]处的参数DatabaseConnection在MongooseModule上下文中可用.ShibeSer



我从这里看了Mongo测试的例子:

该示例测试并模拟了服务中方法的实现,但我还没有做到这一点。我已经提供了getModelToken,但在我的情况下,这似乎并没有起到作用。

这是我收到的错误消息,下面是我的代码片段:

ShibeService › should be defined
Nest can't resolve dependencies of the ShibeModel (?). Please make sure that the argument DatabaseConnection at index [0] is available in the MongooseModule context.
Potential solutions:
- If DatabaseConnection is a provider, is it part of the current MongooseModule?
- If DatabaseConnection is exported from a separate @Module, is that module imported within MongooseModule?
@Module({
imports: [ /* the Module containing DatabaseConnection */ ]
})

ShibeService.Spec.Ts

import { HttpModule } from '@nestjs/axios';
import { Test, TestingModule } from '@nestjs/testing';
import { ShibeService } from './shibe.service';
import { ShibeModule } from './shibe.module';
import { getModelToken } from '@nestjs/mongoose';
import { Shibe } from './schemas/shibe.schema';
describe('ShibeService', () => {
let service: ShibeService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
ShibeService,
{
provide: getModelToken(Shibe.name),
useValue: jest.fn(),
},
],
imports: [HttpModule, ShibeModule],
}).compile();
service = module.get<ShibeService>(ShibeService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

shibe.service.ts

import { Injectable, OnModuleInit } from '@nestjs/common';
import { Model } from 'mongoose';
import { CreateShibe } from './models/create-shibe.model';
import { uniqueNamesGenerator, Config, names } from 'unique-names-generator';
import { Shibe, ShibeDocument } from './schemas/shibe.schema';
import { InjectModel } from '@nestjs/mongoose';
import { HttpService } from '@nestjs/axios';
import { map } from 'rxjs';
import {v4 as uuidv4} from 'uuid';
@Injectable()
export class ShibeService implements OnModuleInit {
apiUrl: string;
shibes: Shibe[];
constructor(
private httpService: HttpService,
@InjectModel(Shibe.name) private readonly shibeModel: Model<ShibeDocument>,

) {
this.apiUrl = 'http://shibe.online/api/shibes';
}
async onModuleInit() {
// when model is initalised
//check if database has shibes, if not populate it with 100 shibes
const shibesInDatabase = await this.shibeModel.count({});
const config: Config = {
dictionaries: [names],
};
if (shibesInDatabase < 20) {
this.httpService
.get<string[]>(`${this.apiUrl}?count=10`)
.pipe(map((response) => response.data))
.subscribe((urls: string[]) => {
const shibes = urls.map((url: string) => {
return {
name: uniqueNamesGenerator(config),
url,
};
});
console.log(...shibes);
this.shibeModel.create(...shibes)
});
}
}
async create(createShibeDto: CreateShibe): Promise<Shibe> {
const createdShibe = await this.shibeModel.create(createShibeDto);
return createdShibe;
}
async findAll(): Promise<Shibe[]> {
return this.shibeModel.find({}).exec();
}
async findOne(id: string): Promise<Shibe> {
return this.shibeModel.findOne({ _id: id }).exec();
}
async delete(id: string) {
const deletedShibe = await this.shibeModel
.findByIdAndRemove({ _id: id })
.exec();
return deletedShibe;
}
}

shibe.module.ts

import { Module } from '@nestjs/common';
import { ShibeService } from './shibe.service';
import { ShibeController } from './shibe.controller';
import { MongooseModule } from '@nestjs/mongoose';
import { Shibe, ShibeSchema } from './schemas/shibe.schema';
import { HttpModule } from '@nestjs/axios';

@Module({
controllers: [ShibeController],
providers: [ShibeService],
imports: [MongooseModule.forFeature([{ name: Shibe.name, schema: ShibeSchema }]), HttpModule],
})
export class ShibeModule {}

shibe.schema

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { ApiProperty } from '@nestjs/swagger';
import { Document } from 'mongoose';
export type ShibeDocument = Shibe & Document;
@Schema()
export class Shibe {
@ApiProperty({ example: 'Dodge', description: 'The shibe dog name' })
@Prop({ required: true })
name: string;
@Prop({ required: true })
@ApiProperty({ example: 'http://image.jpg', description: 'The shibe image url' })
url: string;
@ApiProperty({ example: '12343', description: 'The shibe id' })
@Prop()
id: string;
}
export const ShibeSchema = SchemaFactory.createForClass(Shibe);

我只是在测试该服务是否有效

如果您只是在进行单元测试,我强烈建议不要添加任何imports。您正在测试的类需要的任何提供者都可以使用自定义提供者进行模拟,如本repo中所示。事实上,您已经模拟了@InjectModel(Shibe.name),所以剩下的唯一工作就是为HttpService编写一个自定义提供程序,并从测试设置中删除imports属性和数组。

{
provide: HttpService,
useValue: {
get: () => of({ data: shibeArray })
}
}

这应该足以让你的考试通过。

编辑您的Shibe.Module.ts导入到:导入:[MongooseModule.forFeature([{name:Shibe.name,schema:ShibeSchema}](,HttpModule,ShibeModel]

最新更新