【问题标题】:Mock a mongoose document in Nestjs在 Nestjs 中模拟猫鼬文档
【发布时间】:2019-12-20 21:18:08
【问题描述】:

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

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>

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

【问题讨论】:

    标签: mongodb typescript unit-testing mongoose nestjs


    【解决方案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
    

    【讨论】:

    • 我不知道如何直接与您联系。但是非常感谢您的所有帮助:) 您是否有 Twitter 或任何其他我可以与您联系的社交媒体帐户?不是问你更多,而是直接感谢你。
    • @MattWalterspieler 我有一个 GitHub :)
    猜你喜欢
    • 2021-07-05
    • 1970-01-01
    • 2021-08-11
    • 2020-12-18
    • 2021-05-19
    • 2020-11-18
    • 2018-08-29
    • 2019-08-04
    • 2017-12-30
    相关资源
    最近更新 更多