Co-authored-by: gorbenko.pavel <gorbenko.pavel@tansu.kz> Reviewed-on: http://git.tnsu.kz/timur.gorodetskiy/request-portal/pulls/5
This commit was merged in pull request #5.
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
import { installErrorLogging } from './diagnostics';
|
||||
|
||||
// jsdom не порождает unhandledrejection сам — событие диспатчим руками, как это
|
||||
// сделал бы браузер. Конструктора PromiseRejectionEvent в jsdom нет, поэтому
|
||||
// собираем обычное Event и дописываем reason (слушатель читает только его).
|
||||
function emitRejection(reason: unknown): void {
|
||||
const event = new Event('unhandledrejection') as Event & { reason?: unknown };
|
||||
event.reason = reason;
|
||||
window.dispatchEvent(event);
|
||||
}
|
||||
|
||||
describe('installErrorLogging', () => {
|
||||
let errors: unknown[][];
|
||||
let spy: jest.SpyInstance;
|
||||
|
||||
beforeEach(() => {
|
||||
errors = [];
|
||||
spy = jest.spyOn(console, 'error').mockImplementation((...args: unknown[]) => {
|
||||
errors.push(args);
|
||||
});
|
||||
installErrorLogging();
|
||||
});
|
||||
|
||||
afterEach(() => spy.mockRestore());
|
||||
|
||||
it('печатает сообщение и стек обычной ошибки', () => {
|
||||
emitRejection(new Error('Список недоступен'));
|
||||
|
||||
const text = errors.map((a) => a.join(' ')).join('\n');
|
||||
expect(text).toContain('Список недоступен');
|
||||
expect(text).toContain('Стек');
|
||||
});
|
||||
|
||||
it('не теряет причину, если это не Error, а объект (типичный отказ PnPjs)', () => {
|
||||
emitRejection({ status: 403, message: 'Access denied' });
|
||||
|
||||
const text = errors.map((a) => a.map((x) => JSON.stringify(x)).join(' ')).join('\n');
|
||||
expect(text).toContain('403');
|
||||
expect(text).toContain('Access denied');
|
||||
});
|
||||
|
||||
it('не падает на причине с циклической ссылкой', () => {
|
||||
const cyclic: Record<string, unknown> = { name: 'зацикленное' };
|
||||
cyclic.self = cyclic;
|
||||
|
||||
expect(() => emitRejection(cyclic)).not.toThrow();
|
||||
expect(errors.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('строка-причина попадает в лог как есть', () => {
|
||||
emitRejection('просто текст');
|
||||
expect(errors.map((a) => a.join(' ')).join('\n')).toContain('просто текст');
|
||||
});
|
||||
|
||||
it('повторный вызов не вешает второй слушатель — ошибка не двоится', () => {
|
||||
installErrorLogging();
|
||||
installErrorLogging();
|
||||
|
||||
emitRejection(new Error('однократно'));
|
||||
|
||||
const count = errors.filter((a) => String(a[0]).indexOf('Необработанная ошибка') !== -1).length;
|
||||
expect(count).toBe(1);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user