首页 > 解决方案 > 在 Nestjs 中模拟猫鼬文档

问题描述

我正在尝试在我的 nestjs 应用程序中模拟一个猫鼬文档,然后在我的单元测试中使用它。

基金模拟文件

import { Fund } from '../interfaces/fund.interface';

export const FundMock: Fund = {
  isin: 'FR0000000000',
  name: 'Test',
  currency: 'EUR',
  fund_type: 'uc',
  company: '5cf6697eecb759de13fc2c73',
  fed: true,
};

基金接口.ts

import { Document } from 'mongoose';

export interface Fund extends Document {
  isin: string;
  name: string;
  fed: boolean;
  currency: string;
  fund_type: string;
  company: string;
}

从逻辑上讲,它会输出一个错误,指出缺少 Document 属性。 is missing the following properties from type 'Fund': increment, model, $isDeleted, remove, and 53 more.

在我的测试中,我像这样模拟 getFund() 方法: service.getFund = async () => FundMock;

getFund期待回归Promise<Fund>

那么如何模拟这些属性呢?

标签: mongodbtypescriptunit-testingmongoosenestjs

解决方案


您以错误的方式嘲笑该getFund方法。这是mockgetFund方法的正确方法,您需要使用jest.fn方法来模拟方法。

interface Fund {
  isin: string;
  name: string;
  fed: boolean;
  currency: string;
  fund_type: string;
  company: string;
}

export const FundMock: Fund = {
  isin: 'FR0000000000',
  name: 'Test',
  currency: 'EUR',
  fund_type: 'uc',
  company: '5cf6697eecb759de13fc2c73',
  fed: true
};

class Service {
  public async getFund() {
    return 'real fund data';
  }
}

export { Service };

单元测试:

import { Service, FundMock } from './';

const service = new Service();

describe('Service', () => {
  describe('#getFund', () => {
    it('t1', async () => {
      service.getFund = jest.fn().mockResolvedValueOnce(FundMock);
      const actualValue = await service.getFund();
      expect(actualValue).toEqual(FundMock);
    });
  });
});

单元测试结果:

 PASS  src/mock-function/57492604/index.spec.ts
  Service
    #getFund
      ✓ t1 (15ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        2.464s

推荐阅读