This commit is contained in:
gr
2026-09-28 10:02:07 +08:00
parent d79a2fa489
commit b112dcc6be
303 changed files with 5039 additions and 49659 deletions
@@ -1,240 +0,0 @@
import type { RouteRecordRaw } from '@vben/types';
import { describe, expect, it } from 'vitest';
import { generateAccessible } from '../accessible';
// generateAccessible 会操作传入的 router 实例。这里用最小 stub 覆盖它实际调用的方法:
// - getRoutes(): 返回 [] -> 不存在根路由 '/', 走 router.addRoute 分支
// - addRoute/removeRoute: 空实现
// 我们只断言返回的 accessibleRoutes 上自动生成的 redirect。
function createRouterStub() {
return {
addRoute: () => {},
getRoutes: () => [],
removeRoute: () => {},
} as any;
}
async function generate(routes: RouteRecordRaw[]) {
const { accessibleRoutes } = await generateAccessible('frontend', {
router: createRouterStub(),
routes,
});
return accessibleRoutes;
}
function findByName(
routes: RouteRecordRaw[],
name: string,
): RouteRecordRaw | undefined {
for (const route of routes) {
if (route.name === name) {
return route;
}
if (route.children) {
const found = findByName(route.children as RouteRecordRaw[], name);
if (found) {
return found;
}
}
}
return undefined;
}
describe('generateAccessible - redirect normalization', () => {
it('不为动态参数(:id)首子路由的父级生成 redirect', async () => {
const routes = [
{
name: 'DyeSets',
path: 'dye-sets',
children: [
{
name: 'DyeSetDetail',
path: ':id',
meta: { hideInMenu: true, title: 'detail' },
},
],
meta: { title: 'dye-sets' },
},
] as unknown as RouteRecordRaw[];
const result = await generate(routes);
expect(findByName(result, 'DyeSets')?.redirect).toBeUndefined();
});
it('父级为对象 redirect({name}) 且含 :id 子路由时不抛异常且不生成 redirect', async () => {
const routes = [
{
name: 'Production',
path: '/production',
redirect: { name: 'ProductionTasks' },
children: [
{
name: 'ProductionTasks',
path: 'production-tasks',
children: [
{
name: 'ProductionTaskDetail',
path: ':id',
meta: { hideInMenu: true, title: 'detail' },
},
{
name: 'ProductionTaskMatch',
path: ':id/match',
meta: { hideInMenu: true, title: 'match' },
},
],
meta: { title: 'tasks' },
},
],
meta: { title: 'production' },
},
] as unknown as RouteRecordRaw[];
const result = await generate(routes);
// 顶级对象 redirect 保持不变
expect(findByName(result, 'Production')?.redirect).toEqual({
name: 'ProductionTasks',
});
// :id 首子路由的父级不生成 redirect
expect(findByName(result, 'ProductionTasks')?.redirect).toBeUndefined();
});
it('父级为对象 redirect 时,普通相对首子路由回退用 parent.path 拼接', async () => {
const routes = [
{
name: 'Setting',
path: '/setting',
redirect: { name: 'SettingService' },
children: [
{
name: 'SettingGroup',
path: 'group',
children: [
{
name: 'SettingService',
path: 'service',
meta: { title: 'service' },
},
],
meta: { title: 'group' },
},
],
meta: { title: 'setting' },
},
] as unknown as RouteRecordRaw[];
const result = await generate(routes);
expect(findByName(result, 'SettingGroup')?.redirect).toBe(
'/setting/group/service',
);
});
it('深层嵌套(上游风格)相对路径逐级生成正确的累计绝对 redirect', async () => {
const routes = [
{
name: 'Demos',
path: '/demos',
children: [
{
name: 'NestedDemos',
path: 'nested',
children: [
{
name: 'Menu1Demo',
path: 'menu1',
meta: { title: 'menu1' },
},
{
name: 'Menu2Demo',
path: 'menu2',
children: [
{
name: 'Menu21Demo',
path: 'menu2-1',
meta: { title: 'menu2-1' },
},
],
meta: { title: 'menu2' },
},
],
meta: { title: 'nested' },
},
],
meta: { title: 'demos' },
},
] as unknown as RouteRecordRaw[];
const result = await generate(routes);
// Demos 重定向到第一级子路由,子路由继续级联到叶子
expect(findByName(result, 'Demos')?.redirect).toBe('/demos/nested');
expect(findByName(result, 'NestedDemos')?.redirect).toBe(
'/demos/nested/menu1',
);
expect(findByName(result, 'Menu2Demo')?.redirect).toBe(
'/demos/nested/menu2/menu2-1',
);
});
it('首子路由为绝对路径(/foo)时不生成 redirect', async () => {
const routes = [
{
name: 'Dashboard',
path: '/dashboard',
children: [
{
name: 'Analytics',
path: '/analytics',
meta: { title: 'analytics' },
},
],
meta: { title: 'dashboard' },
},
] as unknown as RouteRecordRaw[];
const result = await generate(routes);
expect(findByName(result, 'Dashboard')?.redirect).toBeUndefined();
});
it('首子路由为空 path 时不生成 redirect', async () => {
const routes = [
{
name: 'HideChildrenParent',
path: 'hide-menu-children',
children: [
{
name: 'HideChildren',
path: '',
meta: { title: 'hide' },
},
],
meta: { title: 'parent' },
},
] as unknown as RouteRecordRaw[];
const result = await generate(routes);
expect(findByName(result, 'HideChildrenParent')?.redirect).toBeUndefined();
});
it('已存在的 redirect 保持不变', async () => {
const routes = [
{
name: 'Custom',
path: '/custom',
redirect: '/custom/keep',
children: [
{
name: 'CustomChild',
path: 'child',
meta: { title: 'child' },
},
],
meta: { title: 'custom' },
},
] as unknown as RouteRecordRaw[];
const result = await generate(routes);
expect(findByName(result, 'Custom')?.redirect).toBe('/custom/keep');
});
});
@@ -1,132 +0,0 @@
import { mount } from '@vue/test-utils';
import { describe, expect, it } from 'vitest';
import { Page } from '..';
describe('page.vue', () => {
it('renders title when passed', () => {
const wrapper = mount(Page, {
props: {
title: 'Test Title',
},
});
expect(wrapper.text()).toContain('Test Title');
});
it('renders description when passed', () => {
const wrapper = mount(Page, {
props: {
description: 'Test Description',
},
});
expect(wrapper.text()).toContain('Test Description');
});
it('renders default slot content', () => {
const wrapper = mount(Page, {
slots: {
default: '<p>Default Slot Content</p>',
},
});
expect(wrapper.html()).toContain('<p>Default Slot Content</p>');
});
it('renders footer slot when showFooter is true', () => {
const wrapper = mount(Page, {
props: {
showFooter: true,
},
slots: {
footer: '<p>Footer Slot Content</p>',
},
});
expect(wrapper.html()).toContain('<p>Footer Slot Content</p>');
});
it('applies the custom contentClass', () => {
const wrapper = mount(Page, {
props: {
contentClass: 'custom-class',
},
});
const contentDiv = wrapper.find('.p-4');
expect(contentDiv.classes()).toContain('custom-class');
});
it('uses flex layout for automatic content height', () => {
const wrapper = mount(Page, {
props: {
autoContentHeight: true,
heightOffset: 12,
title: 'Auto height page',
},
});
const content = wrapper.find('[data-layout-region="page-content"]');
const header = wrapper.find('.border-b');
expect(wrapper.classes()).toContain('min-h-0');
expect(wrapper.classes()).toContain('overflow-hidden');
expect(header.classes()).toContain('shrink-0');
expect(content.exists()).toBe(true);
expect(content.classes()).toContain('min-h-0');
expect(content.classes()).toContain('flex-1');
expect(content.classes()).toContain('overflow-y-auto');
expect(content.attributes('style')).toContain(
'--page-content-height-offset: 12px',
);
expect(content.attributes('style')).not.toContain('--vben-content-height');
});
it('positions the footer according to footerFixed', async () => {
const wrapper = mount(Page, {
slots: {
footer: '<p>Footer</p>',
},
});
const footer = wrapper.find('.bg-card');
expect(footer.classes()).toContain('shrink-0');
expect(footer.classes()).not.toContain('absolute');
await wrapper.setProps({ footerFixed: true });
expect(footer.classes()).toContain('mt-auto');
expect(footer.classes()).toContain('shrink-0');
expect(footer.classes()).not.toContain('absolute');
});
it('does not render title slot if title prop is provided', () => {
const wrapper = mount(Page, {
props: {
title: 'Test Title',
},
slots: {
title: '<p>Title Slot Content</p>',
},
});
expect(wrapper.text()).toContain('Title Slot Content');
expect(wrapper.html()).not.toContain('Test Title');
});
it('does not render description slot if description prop is provided', () => {
const wrapper = mount(Page, {
props: {
description: 'Test Description',
},
slots: {
description: '<p>Description Slot Content</p>',
},
});
expect(wrapper.text()).toContain('Description Slot Content');
expect(wrapper.html()).not.toContain('Test Description');
});
});
@@ -1,176 +0,0 @@
import type { App } from 'vue';
import type { NavigationGuard, NavigationHookAfter, Router } from 'vue-router';
import { createApp } from 'vue';
import { ELEMENT_ID_LAYOUT_SCROLL } from '@vben-core/shared/constants';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { useLayoutScroll } from '../use-layout-scroll';
let activeApp: App | undefined;
function createRouterMock() {
let afterHook: NavigationHookAfter | undefined;
let beforeGuard: NavigationGuard | undefined;
const removeAfterHook = vi.fn();
const removeBeforeGuard = vi.fn();
const router = {
afterEach: vi.fn((hook: NavigationHookAfter) => {
afterHook = hook;
return removeAfterHook;
}),
beforeEach: vi.fn((guard: NavigationGuard) => {
beforeGuard = guard;
return removeBeforeGuard;
}),
} as unknown as Router;
function getHooks() {
if (!afterHook || !beforeGuard) {
throw new Error('Router hooks were not registered');
}
return { afterHook, beforeGuard };
}
return {
getHooks,
removeAfterHook,
removeBeforeGuard,
router,
};
}
function createScrollElement() {
const element = document.createElement('div');
element.id = ELEMENT_ID_LAYOUT_SCROLL;
element.scrollTo = vi.fn();
document.body.append(element);
return element;
}
function mountLayoutScroll(router: Router) {
const host = document.createElement('div');
document.body.append(host);
activeApp = createApp({
setup() {
useLayoutScroll(router);
return () => null;
},
});
activeApp.mount(host);
}
async function runBeforeGuard(guard: NavigationGuard) {
await guard({} as never, {} as never, vi.fn());
}
async function runAfterHook(hook: NavigationHookAfter, hash = '') {
await hook({ hash } as never, {} as never, undefined);
}
afterEach(() => {
activeApp?.unmount();
activeApp = undefined;
document.body.innerHTML = '';
window.history.replaceState({}, '');
vi.restoreAllMocks();
});
describe('useLayoutScroll', () => {
it('should scroll to top after a normal navigation', async () => {
window.history.replaceState({ position: 0 }, '');
const element = createScrollElement();
element.scrollTop = 240;
const routerMock = createRouterMock();
mountLayoutScroll(routerMock.router);
const { afterHook, beforeGuard } = routerMock.getHooks();
await runBeforeGuard(beforeGuard);
window.history.replaceState({ position: 1 }, '');
await runAfterHook(afterHook);
expect(element.scrollTo).toHaveBeenCalledWith({ top: 0 });
});
it('should scroll a hash target into view', async () => {
window.history.replaceState({ position: 0 }, '');
const element = createScrollElement();
const hashTarget = document.createElement('div');
hashTarget.id = 'section';
hashTarget.scrollIntoView = vi.fn();
element.append(hashTarget);
const routerMock = createRouterMock();
mountLayoutScroll(routerMock.router);
const { afterHook } = routerMock.getHooks();
window.history.replaceState({ position: 1 }, '');
await runAfterHook(afterHook, '#section');
expect(hashTarget.scrollIntoView).toHaveBeenCalledWith({
behavior: 'smooth',
block: 'start',
});
expect(element.scrollTo).not.toHaveBeenCalled();
});
it('should ignore matching hash targets outside the layout', async () => {
window.history.replaceState({ position: 0 }, '');
const hostTarget = document.createElement('div');
hostTarget.id = 'section';
hostTarget.scrollIntoView = vi.fn();
document.body.append(hostTarget);
const element = createScrollElement();
const layoutTarget = document.createElement('div');
layoutTarget.id = 'section';
layoutTarget.scrollIntoView = vi.fn();
element.append(layoutTarget);
const routerMock = createRouterMock();
mountLayoutScroll(routerMock.router);
const { afterHook } = routerMock.getHooks();
window.history.replaceState({ position: 1 }, '');
await runAfterHook(afterHook, '#section');
expect(layoutTarget.scrollIntoView).toHaveBeenCalledWith({
behavior: 'smooth',
block: 'start',
});
expect(hostTarget.scrollIntoView).not.toHaveBeenCalled();
});
it('should restore a saved position on history navigation', async () => {
window.history.replaceState({ position: 0 }, '');
const element = createScrollElement();
element.scrollTop = 240;
const routerMock = createRouterMock();
mountLayoutScroll(routerMock.router);
const { afterHook, beforeGuard } = routerMock.getHooks();
await runBeforeGuard(beforeGuard);
window.history.replaceState({ position: 1 }, '');
await runAfterHook(afterHook);
element.scrollTop = 80;
window.history.replaceState({ position: 0 }, '');
await runBeforeGuard(beforeGuard);
await runAfterHook(afterHook);
expect(element.scrollTo).toHaveBeenLastCalledWith({ top: 240 });
});
it('should remove router hooks when the scope is disposed', () => {
window.history.replaceState({ position: 0 }, '');
createScrollElement();
const routerMock = createRouterMock();
mountLayoutScroll(routerMock.router);
activeApp?.unmount();
activeApp = undefined;
expect(routerMock.removeBeforeGuard).toHaveBeenCalledOnce();
expect(routerMock.removeAfterHook).toHaveBeenCalledOnce();
});
});
@@ -1,157 +0,0 @@
import type { AxiosRequestConfig } from 'axios';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { FileDownloader } from './downloader';
describe('fileDownloader', () => {
let fileDownloader: FileDownloader;
const mockAxiosInstance = {
get: vi.fn(),
} as any;
beforeEach(() => {
fileDownloader = new FileDownloader(mockAxiosInstance);
});
it('should create an instance of FileDownloader', () => {
expect(fileDownloader).toBeInstanceOf(FileDownloader);
});
it('should download a file and return a Blob', async () => {
const url = 'https://example.com/file';
const mockBlob = new Blob(['file content'], { type: 'text/plain' });
const mockResponse: Blob = mockBlob;
mockAxiosInstance.get.mockResolvedValueOnce(mockResponse);
const result = await fileDownloader.download(url);
expect(result).toBeInstanceOf(Blob);
expect(result).toEqual(mockBlob);
expect(mockAxiosInstance.get).toHaveBeenCalledWith(url, {
method: 'GET',
responseType: 'blob',
responseReturn: 'body',
});
});
it('should merge provided config with default config', async () => {
const url = 'https://example.com/file';
const mockBlob = new Blob(['file content'], { type: 'text/plain' });
const mockResponse: Blob = mockBlob;
mockAxiosInstance.get.mockResolvedValueOnce(mockResponse);
const customConfig: AxiosRequestConfig = {
headers: { 'Custom-Header': 'value' },
};
const result = await fileDownloader.download(url, customConfig);
expect(result).toBeInstanceOf(Blob);
expect(result).toEqual(mockBlob);
expect(mockAxiosInstance.get).toHaveBeenCalledWith(url, {
...customConfig,
method: 'GET',
responseType: 'blob',
responseReturn: 'body',
});
});
it('should handle errors gracefully', async () => {
const url = 'https://example.com/file';
mockAxiosInstance.get.mockRejectedValueOnce(new Error('Network Error'));
await expect(fileDownloader.download(url)).rejects.toThrow('Network Error');
});
it('should handle empty URL gracefully', async () => {
const url = '';
mockAxiosInstance.get.mockRejectedValueOnce(
new Error('Request failed with status code 404'),
);
await expect(fileDownloader.download(url)).rejects.toThrow(
'Request failed with status code 404',
);
});
it('should handle null URL gracefully', async () => {
const url = null as unknown as string;
mockAxiosInstance.get.mockRejectedValueOnce(
new Error('Request failed with status code 404'),
);
await expect(fileDownloader.download(url)).rejects.toThrow(
'Request failed with status code 404',
);
});
});
describe('fileDownloader use other method', () => {
let fileDownloader: FileDownloader;
it('should call request using get', async () => {
const url = 'https://example.com/file';
const mockBlob = new Blob(['file content'], { type: 'text/plain' });
const mockResponse: Blob = mockBlob;
const mockAxiosInstance = {
request: vi.fn(),
} as any;
fileDownloader = new FileDownloader(mockAxiosInstance);
mockAxiosInstance.request.mockResolvedValueOnce(mockResponse);
const result = await fileDownloader.download(url);
expect(result).toBeInstanceOf(Blob);
expect(result).toEqual(mockBlob);
expect(mockAxiosInstance.request).toHaveBeenCalledWith(url, {
method: 'GET',
responseType: 'blob',
responseReturn: 'body',
});
});
it('should call post', async () => {
const url = 'https://example.com/file';
const mockAxiosInstance = {
post: vi.fn(),
} as any;
fileDownloader = new FileDownloader(mockAxiosInstance);
const customConfig: AxiosRequestConfig = {
method: 'POST',
data: { name: 'aa' },
};
await fileDownloader.download(url, customConfig);
expect(mockAxiosInstance.post).toHaveBeenCalledWith(
url,
{ name: 'aa' },
{
method: 'POST',
responseType: 'blob',
responseReturn: 'body',
},
);
});
it('should handle errors gracefully', async () => {
const url = 'https://example.com/file';
const mockAxiosInstance = {
post: vi.fn(),
} as any;
fileDownloader = new FileDownloader(mockAxiosInstance);
await expect(() =>
fileDownloader.download(url, { method: 'postt' }),
).rejects.toThrow(
'RequestClient does not support method "POSTT". Please ensure the method is properly implemented in your RequestClient instance.',
);
});
});
@@ -1,142 +0,0 @@
import type { RequestClient } from '../request-client';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { SSE } from './sse';
// 模拟 TextDecoder
const OriginalTextDecoder = globalThis.TextDecoder;
beforeEach(() => {
vi.stubGlobal(
'TextDecoder',
class {
private decoder = new OriginalTextDecoder();
decode(value: Uint8Array, opts?: any) {
return this.decoder.decode(value, opts);
}
},
);
});
// 创建 fetch mock
const createFetchMock = (chunks: string[], ok = true) => {
const encoder = new TextEncoder();
let index = 0;
return vi.fn().mockResolvedValue({
ok,
status: ok ? 200 : 500,
body: {
getReader: () => ({
read: async () => {
if (index < chunks.length) {
return { done: false, value: encoder.encode(chunks[index++]) };
}
return { done: true, value: undefined };
},
}),
},
});
};
describe('sSE', () => {
let client: RequestClient;
let sse: SSE;
beforeEach(() => {
vi.restoreAllMocks();
client = {
getBaseUrl: () => 'http://localhost',
instance: {
interceptors: {
request: {
handlers: [],
},
},
},
} as unknown as RequestClient;
sse = new SSE(client);
});
it('should call requestSSE when postSSE is used', async () => {
const spy = vi.spyOn(sse, 'requestSSE').mockResolvedValue(undefined);
await sse.postSSE('/test', { foo: 'bar' }, { headers: { a: '1' } });
expect(spy).toHaveBeenCalledWith(
'/test',
{ foo: 'bar' },
{
headers: { a: '1' },
method: 'POST',
},
);
});
it('should throw error if fetch response not ok', async () => {
vi.stubGlobal('fetch', createFetchMock([], false));
await expect(sse.requestSSE('/bad')).rejects.toThrow(
'HTTP error! status: 500',
);
});
it('should trigger onMessage and onEnd callbacks', async () => {
const messages: string[] = [];
const onMessage = vi.fn((msg: string) => messages.push(msg));
const onEnd = vi.fn();
vi.stubGlobal('fetch', createFetchMock(['hello', ' world']));
await sse.requestSSE('/sse', undefined, { onMessage, onEnd });
expect(onMessage).toHaveBeenCalledTimes(2);
expect(messages.join('')).toBe('hello world');
// onEnd 不再带参数
expect(onEnd).toHaveBeenCalled();
});
it('should apply request interceptors', async () => {
const interceptor = vi.fn(async (config) => {
config.headers['x-test'] = 'intercepted';
return config;
});
(client.instance.interceptors.request as any).handlers.push({
fulfilled: interceptor,
});
// 创建 fetch mock,并挂到全局
const fetchMock = createFetchMock(['data']);
vi.stubGlobal('fetch', fetchMock);
await sse.requestSSE('/sse', undefined, {});
expect(interceptor).toHaveBeenCalled();
expect(fetchMock).toHaveBeenCalledWith(
'http://localhost/sse',
expect.objectContaining({
headers: expect.any(Headers),
}),
);
const calls = fetchMock.mock?.calls;
expect(calls).toBeDefined();
expect(calls?.length).toBeGreaterThan(0);
const init = calls?.[0]?.[1] as RequestInit;
expect(init).toBeDefined();
const headers = init?.headers as Headers;
expect(headers?.get('x-test')).toBe('intercepted');
expect(headers?.get('accept')).toBe('text/event-stream');
});
it('should throw error when no reader', async () => {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({
ok: true,
status: 200,
body: null,
}),
);
await expect(sse.requestSSE('/sse')).rejects.toThrow('No reader');
});
});
@@ -1,118 +0,0 @@
import type { AxiosRequestConfig, AxiosResponse } from 'axios';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { FileUploader } from './uploader';
describe('fileUploader', () => {
let fileUploader: FileUploader;
// Mock the AxiosInstance
const mockAxiosInstance = {
post: vi.fn(),
} as any;
beforeEach(() => {
fileUploader = new FileUploader(mockAxiosInstance);
});
it('should create an instance of FileUploader', () => {
expect(fileUploader).toBeInstanceOf(FileUploader);
});
it('should upload a file and return the response', async () => {
const url = 'https://example.com/upload';
const file = new File(['file content'], 'test.txt', { type: 'text/plain' });
const mockResponse: AxiosResponse = {
config: {} as any,
data: { success: true },
headers: {},
status: 200,
statusText: 'OK',
};
(
mockAxiosInstance.post as unknown as ReturnType<typeof vi.fn>
).mockResolvedValueOnce(mockResponse);
const result = await fileUploader.upload(url, { file });
expect(result).toEqual(mockResponse);
expect(mockAxiosInstance.post).toHaveBeenCalledWith(
url,
expect.any(FormData),
{
headers: {
'Content-Type': 'multipart/form-data',
},
},
);
});
it('should merge provided config with default config', async () => {
const url = 'https://example.com/upload';
const file = new File(['file content'], 'test.txt', { type: 'text/plain' });
const mockResponse: AxiosResponse = {
config: {} as any,
data: { success: true },
headers: {},
status: 200,
statusText: 'OK',
};
(
mockAxiosInstance.post as unknown as ReturnType<typeof vi.fn>
).mockResolvedValueOnce(mockResponse);
const customConfig: AxiosRequestConfig = {
headers: { 'Custom-Header': 'value' },
};
const result = await fileUploader.upload(url, { file }, customConfig);
expect(result).toEqual(mockResponse);
expect(mockAxiosInstance.post).toHaveBeenCalledWith(
url,
expect.any(FormData),
{
headers: {
'Content-Type': 'multipart/form-data',
'Custom-Header': 'value',
},
},
);
});
it('should handle errors gracefully', async () => {
const url = 'https://example.com/upload';
const file = new File(['file content'], 'test.txt', { type: 'text/plain' });
(
mockAxiosInstance.post as unknown as ReturnType<typeof vi.fn>
).mockRejectedValueOnce(new Error('Network Error'));
await expect(fileUploader.upload(url, { file })).rejects.toThrow(
'Network Error',
);
});
it('should handle empty URL gracefully', async () => {
const url = '';
const file = new File(['file content'], 'test.txt', { type: 'text/plain' });
(
mockAxiosInstance.post as unknown as ReturnType<typeof vi.fn>
).mockRejectedValueOnce(new Error('Request failed with status code 404'));
await expect(fileUploader.upload(url, { file })).rejects.toThrow(
'Request failed with status code 404',
);
});
it('should handle null URL gracefully', async () => {
const url = null as unknown as string;
const file = new File(['file content'], 'test.txt', { type: 'text/plain' });
(
mockAxiosInstance.post as unknown as ReturnType<typeof vi.fn>
).mockRejectedValueOnce(new Error('Request failed with status code 404'));
await expect(fileUploader.upload(url, { file })).rejects.toThrow(
'Request failed with status code 404',
);
});
});
@@ -1,93 +0,0 @@
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { RequestClient } from './request-client';
describe('requestClient', () => {
let mock: MockAdapter;
let requestClient: RequestClient;
beforeEach(() => {
mock = new MockAdapter(axios);
requestClient = new RequestClient();
});
afterEach(() => {
mock.reset();
});
it('should successfully make a GET request', async () => {
mock.onGet('test/url').reply(200, { data: 'response' });
const response = await requestClient.get('test/url');
expect(response.data).toEqual({ data: 'response' });
});
it('should successfully make a POST request', async () => {
const postData = { key: 'value' };
const mockData = { data: 'response' };
mock.onPost('/test/post', postData).reply(200, mockData);
const response = await requestClient.post('/test/post', postData);
expect(response.data).toEqual(mockData);
});
it('should successfully make a PUT request', async () => {
const putData = { key: 'updatedValue' };
const mockData = { data: 'updated response' };
mock.onPut('/test/put', putData).reply(200, mockData);
const response = await requestClient.put('/test/put', putData);
expect(response.data).toEqual(mockData);
});
it('should successfully make a DELETE request', async () => {
const mockData = { data: 'delete response' };
mock.onDelete('/test/delete').reply(200, mockData);
const response = await requestClient.delete('/test/delete');
expect(response.data).toEqual(mockData);
});
it('should handle network errors', async () => {
mock.onGet('/test/error').networkError();
await expect(requestClient.get('/test/error')).rejects.toMatchObject({
isAxiosError: true,
message: 'Network Error',
});
});
it('should handle timeout', async () => {
mock.onGet('/test/timeout').timeout();
await expect(requestClient.get('/test/timeout')).rejects.toMatchObject({
isAxiosError: true,
code: 'ECONNABORTED',
});
});
it('should successfully upload a file', async () => {
const fileData = new Blob(['file contents'], { type: 'text/plain' });
mock.onPost('/test/upload').reply((config) => {
return config.data instanceof FormData && config.data.has('file')
? [200, { data: 'file uploaded' }]
: [400, { error: 'Bad Request' }];
});
const response = await requestClient.upload('/test/upload', {
file: fileData,
});
expect(response.data).toEqual({ data: 'file uploaded' });
});
it('should successfully download a file as a blob', async () => {
const mockFileContent = new Blob(['mock file content'], {
type: 'text/plain',
});
mock.onGet('/test/download').reply(200, mockFileContent);
const res = await requestClient.download<any>('/test/download');
expect(res.data).toBeInstanceOf(Blob);
});
});