axios-miniprogram/test/core/InterceptorManager.test.ts

78 lines
1.7 KiB
TypeScript
Raw Normal View History

2023-04-05 08:40:00 +08:00
import { describe, test, expect, vi } from 'vitest';
2023-04-09 15:20:10 +08:00
import InterceptorManager from '@/core/InterceptorManager';
2023-04-05 08:40:00 +08:00
describe('src/core/InterceptorManager.ts', () => {
test('应该有这些实例属性', () => {
const i = new InterceptorManager();
expect(i.use).toBeTypeOf('function');
expect(i.eject).toBeTypeOf('function');
expect(i.forEach).toBeTypeOf('function');
});
test('应该可以添加和删除拦截处理函数', () => {
const i = new InterceptorManager();
const res = vi.fn();
const rej = vi.fn();
const cb = vi.fn();
2023-04-17 19:27:44 +08:00
expect(i.size).toBe(0);
2023-04-05 08:40:00 +08:00
const id = i.use(res, rej);
2023-04-17 19:27:44 +08:00
expect(i.size).toBe(1);
2023-04-05 08:40:00 +08:00
i.forEach(({ resolved, rejected }) => {
expect(resolved).toBe(res);
expect(rejected).toBe(rej);
});
i.eject(id);
i.forEach(cb);
2023-04-17 19:27:44 +08:00
expect(i.size).toBe(0);
2023-04-05 08:40:00 +08:00
expect(cb).not.toBeCalled();
});
2023-04-17 19:27:44 +08:00
test('应该可以清理所有拦截处理函数', () => {
2023-04-05 08:40:00 +08:00
const i = new InterceptorManager();
2023-04-17 19:27:44 +08:00
const res = vi.fn();
const rej = vi.fn();
2023-04-05 08:40:00 +08:00
2023-04-17 19:27:44 +08:00
expect(i.size).toBe(0);
2023-04-05 08:40:00 +08:00
2023-04-17 19:27:44 +08:00
i.use(res, rej);
i.use(res, rej);
i.use(res, rej);
expect(i.size).toBe(3);
i.clear();
expect(i.size).toBe(0);
2023-04-05 08:40:00 +08:00
});
2023-04-17 19:27:44 +08:00
test('应该可以调用 forEach', () => {
2023-04-05 08:40:00 +08:00
const i = new InterceptorManager();
const res1 = vi.fn();
const rej1 = vi.fn();
const res2 = vi.fn();
const rej2 = vi.fn();
const cb = vi.fn();
i.use(res1, rej1);
i.use(res2, rej2);
2023-04-17 19:27:44 +08:00
i.forEach(cb);
2023-04-05 08:40:00 +08:00
expect(cb.mock.calls[0][0]).toEqual({
resolved: res1,
rejected: rej1,
});
2023-04-17 19:27:44 +08:00
expect(cb.mock.calls[1][0]).toEqual({
resolved: res2,
rejected: rej2,
});
2023-04-05 08:40:00 +08:00
});
});