Reputation: 2181
I'm trying to mock a mongoose document in my nestjs app to then use it in my unit test.
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;
}
Logically it outputs an error that says that Document properties are missing.
is missing the following properties from type 'Fund': increment, model, $isDeleted, remove, and 53 more.
In my test I mock the getFund() method like so:
service.getFund = async () => FundMock;
getFund
expects to return Promise<Fund>
So how can I mock these properties?
Upvotes: 1
Views: 1431
Reputation: 102587
You mocked the getFund
method in the wrong way. Here is the correct way to mock getFund
method, you need to use jest.fn
method to mock the method.
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 };
Unit test:
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);
});
});
});
Unit test result:
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
Upvotes: 3