mongodb - 在 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>
那么如何模拟这些属性呢?
解决方案
您以错误的方式嘲笑该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
推荐阅读
- android - Android MediaPlayer:在 API 19 上出现错误 (1,-1004)?
- azure - Azure Webjob 无故停止
- flutter - 如何从 API 获取特定数据到 Flutter 应用程序中
- mysql - 如何使用 LINQ 从数据库中搜索和项目
- reporting-services - SSRS - 添加总数的百分比?
- php - 在单个产品页面上的“已添加到购物车”消息中添加带有指向主类别链接的自定义按钮
- javascript - 如何从包含相同数字的数组中获取所有索引值?
- java - 如何从变量中获取字符串值并发送到搜索框
- javascript - 如何使用一次迭代的结果来重新迭代?
- logstash - 如何使用logstash删除xml中的行