【问题标题】:How to test mongoose in NestJS Service?如何在 NestJS 服务中测试猫鼬?
【发布时间】:2019-12-22 00:12:58
【问题描述】:

我想从我的服务中测试getFund() 方法。我使用默认使用 jest 的 NestJS。 我不知道如何用玩笑来测试这条线:return await this.fundModel.findById(id);。有什么想法吗?

import { Injectable } from '@nestjs/common';
import { Model } from 'mongoose';
import { Fund } from '../../funds/interfaces/fund.interface';
import { InjectModel } from '@nestjs/mongoose';


@Injectable()
export class FundService {
  constructor(
    @InjectModel('Fund')
    private readonly fundModel: Model<Fund>,
  ) {}

  /*****
    SOME MORE CODE
  ****/

  async getFund(id: string): Promise<Fund> {
    return await this.fundModel.findById(id);
  }
}

编辑

感谢 slideshowp2 的回答,我写了这个测试。

describe('#getFund', () => {
    it('should return a Promise of Fund', async () => {
      let spy = jest.spyOn(service, 'getFund').mockImplementation(async () => {
        return await Promise.resolve(FundMock as Fund);
      });
      service.getFund('');
      expect(service.getFund).toHaveBeenCalled();
      expect(await service.getFund('')).toEqual(FundMock);
      spy.mockRestore();
    });
  });

问题是我在覆盖率报告中得到了这个结果:

当我悬停该行时,我得到statement not covered

【问题讨论】:

    标签: node.js unit-testing mongoose jestjs nestjs


    【解决方案1】:

    您的getFund 方法中只有一个语句return await this.fundModel.findById(id);。没有其他代码逻辑,这意味着您可以进行的单元测试只是模拟 this.fundModel.findById(id) 方法和测试 它.toBeCalledWith(someId)

    我们应该模拟每个方法并测试您的getFund 方法中的代码逻辑。目前,没有其他代码逻辑。

    例如

    
     async getFund(id: string): Promise<Fund> {
        // we should mock this, because we should make an isolate environment for testing `getFund`
        const fundModel = await this.fundModel.findById(id); 
        // Below branch we should test based on your mock value: fundModel
        if(fundModel) {
          return true
        }
        return false
      }
    
    

    更新

    例如:

    describe('#findById', () => {
        it('should find ad subscription by id correctly', async () => {
          (mockOpts.adSubscriptionDataSource.findById as jestMock).mockResolvedValueOnce({ adSubscriptionId: 1 });
          const actualValue = await adSubscriptionService.findById(1);
          expect(actualValue).toEqual({ adSubscriptionId: 1 });
          expect(mockOpts.adSubscriptionDataSource.findById).toBeCalledWith(1);
        });
      });
    

    测试覆盖率报告:

    【讨论】:

    • 您好幻灯片p2。非常感谢您的回答。我尝试了你告诉我的内容,但我的报道报告中仍然出现错误。你知道为什么以及如何解决这个问题吗?
    猜你喜欢
    • 2021-08-11
    • 2019-08-04
    • 1970-01-01
    • 2019-10-10
    • 2021-09-18
    • 2020-11-08
    • 1970-01-01
    • 2018-08-29
    • 2021-08-24
    相关资源
    最近更新 更多