mongodb 请确保位于索引[0]处的参数DatabaseConnection在MongooseModule上下文中可用,ShibeService规范

juud5qan  于 2022-11-03  发布在  Go
关注(0)|答案(2)|浏览(201)

我看过here:中有关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);

我只是在测试服务是否正常工作

bgibtngc

bgibtngc1#

如果您只是在进行单元测试,我强烈建议您a不要 * 添加任何imports。您正在测试的类需要的任何提供程序都可以用custom provider模拟为shown in this repo。实际上,您已经模拟了@InjectModel(Shibe.name),因此剩下要做的唯一事情就是为HttpService编写一个自定义提供程序,并删除imports属性和数组从您的测试设置。

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

这应该足够让你通过考试了。

4smxwvx5

4smxwvx52#

编辑您的Shibe.Module.ts汇入到这个:导入:[MongooseModule. for功能([{名称:Shibe.name、HttpModule、ShibeModel]中的一个或多个模块,并将其添加到数据库中。

相关问题