在Nestjs中模拟猫鼬文档

时间:2019-08-14 10:07:58

标签: mongodb typescript unit-testing mongoose nestjs

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

fund.mock.ts

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

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

fund.interface.ts

import { Document } from 'mongoose';

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

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

在我的测试中,我模拟了getFund()方法,如下所示: service.getFund = async () => FundMock;

getFund期望返回Promise<Fund>

那么我该如何模拟这些属性?

1 个答案:

答案 0 :(得分:1)

您以错误的方式嘲笑了getFund方法。这是模拟getFund方法的正确方法,您需要使用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