Вот решение для модульного тестирования:
index.ts
:
class Service {
private dataSourceService;
constructor(dataSourceService) {
this.dataSourceService = dataSourceService;
}
public async callDataSourceCommand(dialogData: any, RecipeId: string) {
const id = '1';
const collection = [];
const gridItems = await this.dataSourceService.myPromiseMethod(id, collection);
this.updateGrid(JSON.parse(gridItems));
}
private updateGrid(gridItems: any) {}
}
export { Service };
datasourceService.ts
:
class DataSourceService {
public myPromiseMethod(id, collection) {
return JSON.stringify({});
}
}
export { DataSourceService };
index.test.ts
:
import { Service } from './';
describe('60446313', () => {
it('should pass', async () => {
const gridItemsMock = JSON.stringify({
selectedOrder: {
earlierStartTime: '2/5/2020',
__id: 'orderId123',
},
Collection: [
{
__id: 'b1order 1',
resName: 'New recipe_V1.0',
plannedQuantity: '3',
resId: 'ns=6;s=4/ProjectData/1',
actualQuantity: '1',
description: 'batchDesc',
},
],
});
const dataSourceServiceMock = {
myPromiseMethod: jest.fn().mockResolvedValueOnce(gridItemsMock),
};
const parseSpy = jest.spyOn(JSON, 'parse');
const service = new Service(dataSourceServiceMock);
await service.callDataSourceCommand('dialogData', '1');
expect(dataSourceServiceMock.myPromiseMethod).toBeCalledWith('1', []);
expect(parseSpy).toBeCalledWith(gridItemsMock);
});
});
Результаты модульных испытаний с отчетом о покрытии:
PASS stackoverflow/60446313/index.test.ts
60446313
✓ should pass (9ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.ts | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 4.509s, estimated 6s