import axios from 'axios'; import { initAjaxHandlersCommon } from '../ajax-handlers-common'; import { initAjaxHandlersCSRFToken } from '../ajax-handlers-csrf-token'; import { initAjaxHandlersParseDates } from '../ajax-handlers-parse-dates'; jest.mock('axios', () => ({ defaults: {}, interceptors: { request: { use: jest.fn() } } })); jest.mock('../ajax-handlers-csrf-token', () => ({ initAjaxHandlersCSRFToken: jest.fn() })); jest.mock('../ajax-handlers-parse-dates'); type RequestInterceptorConfig = Parameters< NonNullable[0]> >[0]; describe(`[ajax-handlers] ${initAjaxHandlersCommon.name}`, () => { const subject = () => initAjaxHandlersCommon(); test('initializes csrf handlers', () => { subject(); expect(initAjaxHandlersCSRFToken).toHaveBeenCalled(); }); test('initializes parse dates handlers', () => { subject(); expect(initAjaxHandlersParseDates).toHaveBeenCalled(); }); describe('request interceptor', () => { let config: RequestInterceptorConfig; beforeAll(() => initAjaxHandlersCommon()); beforeEach(() => (config = { url: 'http://example.com/foo' } as RequestInterceptorConfig)); const subject = () => { const interceptors = jest.mocked(axios.interceptors.request.use).mock.calls; let configResult = config; for (const interceptor of interceptors) { configResult = interceptor[0]?.(configResult) as RequestInterceptorConfig; } return configResult; }; test('adds Content-Type and Accept headers', () => { expect(subject()).toEqual({ ...config, headers: { 'Content-Type': 'application/json;charset=UTF-8', 'Accept': 'application/json', }, }); }); describe('when request contains FormData', () => { beforeEach(() => (config.data = new FormData())); test('does not add headers', () => { expect(subject()).toEqual(config); }); }); }); describe('validateStatus handler', () => { beforeAll(() => initAjaxHandlersCommon()); const subject = (status: number) => axios.defaults.validateStatus?.(status); test.each([ { status: 100, expected: false }, { status: 200, expected: true }, { status: 300, expected: true }, { status: 400, expected: false }, { status: 500, expected: false }, ])(`status $status returns $expected`, ({ status, expected }) => { expect(subject(status)).toBe(expected); }); }); });