Вы почти у цели. Вот решение для модульного теста:
index.ts
:
export async function doStuff() {
try {
const granted = await navigator.storage.persist();
if (granted) {
console.log('Storage is now going to be persistent...', granted);
}
} catch (error) {
const errorMessage = `Client did not allow storage to be persistent..${error.message}`;
throw new Error(errorMessage);
}
}
index.test.ts
:
import { doStuff } from './';
describe('61069460', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it('should granted', async () => {
const persistMock = jest.fn().mockResolvedValueOnce(true);
Object.defineProperty(navigator, 'storage', {
value: {
persist: persistMock,
},
configurable: true,
});
const logSpy = jest.spyOn(console, 'log');
await doStuff();
expect(persistMock).toBeCalledTimes(1);
expect(logSpy).toBeCalledWith('Storage is now going to be persistent...', true);
});
it('should throw custom error', async () => {
const mError = new Error('IO');
const persistMock = jest.fn().mockRejectedValueOnce(mError);
Object.defineProperty(navigator, 'storage', {
value: {
persist: persistMock,
},
configurable: true,
});
const logSpy = jest.spyOn(console, 'log');
await expect(doStuff()).rejects.toThrowError('Client did not allow storage to be persistent..IO');
expect(persistMock).toBeCalledTimes(1);
expect(logSpy).not.toBeCalled();
});
});
Результаты модульного теста с отчетом о покрытии:
PASS stackoverflow/61069460/index.test.ts (9.134s)
61069460
✓ should granted (15ms)
✓ should throw custom error (3ms)
console.log node_modules/jest-environment-enzyme/node_modules/jest-mock/build/index.js:866
Storage is now going to be persistent... true
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 50 | 100 | 100 |
index.ts | 100 | 50 | 100 | 100 | 4
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 10.135s
исходный код: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/61069460