To simulate a `getter` for the `list` property, you can utilize `jest.spyOn`. The solution is outlined below:
Directory structure:
.
├── dependency-service-instance.ts
├── dependency-service.ts
├── my-service.spec.ts
└── my-service.ts
dependency-service.ts
:
export class DependencyService {
private _list: any[] = [];
public get list(): any[] {
return this._list;
}
}
dependency-service-instance.ts
:
import { DependencyService } from './dependency-service';
export const dependentService = new DependencyService();
my-service.ts
:
import { dependentService } from './dependency-service-instance';
export function myFunction(): string {
const list = dependentService.list;
if (!list.length) {
throw new Error('list is empty');
}
return 'xyz';
}
my-service.spec.ts
:
import { myFunction } from './my-service';
import { dependentService } from './dependency-service-instance';
describe('myFunction', () => {
it('should return a string if dependentService does not provide an empty list', () => {
const spy = jest.spyOn(dependentService, 'list', 'get').mockReturnValueOnce([{}]);
const actualValue = myFunction();
expect(actualValue).toBe('xyz');
expect(spy).toBeCalledTimes(1);
spy.mockRestore();
});
it('should throw an error if dependentService provides an empty list', () => {
const spy = jest.spyOn(dependentService, 'list', 'get').mockReturnValueOnce([]);
expect(() => myFunction()).toThrowError(new Error('list is empty'));
expect(spy).toBeCalledTimes(1);
spy.mockRestore();
});
});
Unit test results with coverage report:
PASS src/stackoverflow/58073589/my-service.spec.ts (9.08s)
myFunction
✓ should return a string if dependentService does not provide an empty list (5ms)
✓ should throw an error if dependentService provides an empty list (3ms)
--------------------------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
--------------------------------|----------|----------|----------|----------|-------------------|
All files | 92.86 | 100 | 66.67 | 92.31 | |
dependency-service-instance.ts | 100 | 100 | 100 | 100 | |
dependency-service.ts | 83.33 | 100 | 50 | 80 | 4 |
my-service.ts | 100 | 100 | 100 | 100 | |
--------------------------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 10.806s
For the complete demonstration, visit: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58073589