NestJS + Mongoose:如何测试 document(data).save()?

Nor*_*ler 5 unit-testing mongoose typescript jestjs nestjs

由于我使用了一些抽象,这里的代码只接收一个 User,将其更改为 Mongo 格式(又名在其他地方生成的 id 中添加下斜杠),保存并返回保存的 User,id 上不带下斜杠:

  constructor(
    @InjectModel('User')
    private readonly service: typeof Model
  ) { }

  async saveUser(user: User): Promise<User> {
    const mongoUser = this.getMongoUser(user);
    const savedMongoUser = await new this.service(mongoUser).save();
    return this.toUserFormat(savedMongoUser);
  }
Run Code Online (Sandbox Code Playgroud)

我正在尝试的测试:

  beforeEach(async () => {
        const module: TestingModule = await Test.createTestingModule({
          providers: [
            MongoUserRepository,
            {
              provide: getModelToken('User'),
              useValue: { ... }, // all used functions with jest.fn()
            },
          ],
        }).compile();
    service = module.get<MongoUserRepository>(MongoUserRepository);
    model = module.get<Model<UserDocument>>(getModelToken('User'));
  });

  it('should save new user', async () => {
    jest.spyOn(model, 'save').mockReturnValue({
      save: jest.fn().mockResolvedValueOnce(mockMongoFormat)
    } as any);

    const foundMock = await service.saveUser(mockUserFormat);
    expect(foundMock).toEqual(mockUserFormat);
  });
Run Code Online (Sandbox Code Playgroud)

问题:

No overload matches this call.
  Overload 1 of 4, '(object: Model<UserDocument, {}>, method: "model" | "remove" | "deleteOne" | "init" | "populate" | "replaceOne" | "update" | "updateOne" | "addListener" | "on" | ... 45 more ... | "where"): SpyInstance<...>', gave the following error.
    Argument of type '"save"' is not assignable to parameter of type '"model" | "remove" | "deleteOne" | "init" | "populate" | "replaceOne" | "update" | "updateOne" | "addListener" | "on" | "once" | "removeListener" | "off" | "removeAllListeners" | ... 41 more ... | "where"'.
  Overload 2 of 4, '(object: Model<UserDocument, {}>, method: "collection"): SpyInstance<Collection, [name: string, conn: Connection, opts?: any]>', gave the following error.
    Argument of type '"save"' is not assignable to parameter of type '"collection"'.ts(2769)
Run Code Online (Sandbox Code Playgroud)

尝试使用“new”也是行不通的:

No overload matches this call.
  Overload 1 of 4, '(object: Model<UserDocument, {}>, method: "find" | "watch" | "translateAliases" | "bulkWrite" | "model" | "$where" | "aggregate" | "count" | "countDocuments" | ... 46 more ... | "eventNames"): SpyInstance<...>', gave the following error.
    Argument of type '"new"' is not assignable to parameter of type '"find" | "watch" | "translateAliases" | "bulkWrite" | "model" | "$where" | "aggregate" | "count" | "countDocuments" | "estimatedDocumentCount" | "create" | "createCollection" | ... 43 more ... | "eventNames"'.
  Overload 2 of 4, '(object: Model<UserDocument, {}>, method: "collection"): SpyInstance<Collection, [name: string, conn: Connection, opts?: any]>', gave the following error.
    Argument of type '"new"' is not assignable to parameter of type '"collection"'.
Run Code Online (Sandbox Code Playgroud)

我可能可以更改实现...但真的很想知道在这种情况下该怎么做...我应该如何模拟该函数?

Nor*_*ler 1

放弃了一段时间后,回来做了这个:

async saveUser ( user: User ): Promise<User> {
    const mongoUser = this.getMongoUser(user);
    const savedMongoUser = await this.service.create( mongoUser );
    return this.toUserFormat(savedMongoUser);
}
Run Code Online (Sandbox Code Playgroud)

从 new service(doc).save() 更改为 service.create(doc)

通过的测试变成:

  it( 'should save new user', async () => {
    jest.spyOn( model, 'create' ).mockImplementation(
      jest.fn().mockResolvedValueOnce( mockMongoFormat )
    );
    const foundMock = await service.saveUser( mockUserFormat );
    expect( foundMock ).toEqual( mockUserFormat );
  } );
Run Code Online (Sandbox Code Playgroud)

有了这个... 100% 的覆盖率。好的。 在此输入图像描述