Вот решение для модульного тестирования:
index.ts
:
import { obj } from './obj';
export function main() {
return obj.DataTable().columns().data().eq().indexOf();
}
obj.ts
:
export const obj = {
DataTable: () => {
return {
columns: () => {
return {
data: () => {
return {
eq: () => {
return {
indexOf: () => 'real data',
};
},
};
},
};
},
};
},
};
index.test.ts
:
import { main } from './';
import { obj } from './obj';
describe('61396089', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it('should pass', () => {
const mockDataTable = {
columns: jest.fn().mockReturnThis(),
data: jest.fn().mockReturnThis(),
eq: jest.fn().mockReturnThis(),
indexOf: jest.fn().mockReturnValueOnce('fake data'),
};
jest.spyOn(obj, 'DataTable').mockImplementationOnce(() => mockDataTable);
const actual = main();
expect(actual).toBe('fake data');
expect(mockDataTable.columns).toBeCalledTimes(1);
expect(mockDataTable.data).toBeCalledTimes(1);
expect(mockDataTable.eq).toBeCalledTimes(1);
expect(mockDataTable.indexOf).toBeCalledTimes(1);
});
});
результаты модульных испытаний с отчетом о покрытии:
PASS stackoverflow/61396089/index.test.ts (20.978s)
61396089
✓ should pass (8ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 44.44 | 100 | 16.67 | 44.44 |
index.ts | 100 | 100 | 100 | 100 |
obj.ts | 16.67 | 100 | 0 | 16.67 | 3-10
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 23.889s
исходный код: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/61396089