axios-miniprogram/test/axios.test.ts

69 lines
1.6 KiB
TypeScript
Raw Permalink Normal View History

2023-04-02 23:27:45 +08:00
import { describe, test, expect } from 'vitest';
2023-04-22 16:12:32 +08:00
import {
mockAdapter,
mockAdapterError,
testEachMethods,
} from 'scripts/test.utils';
2023-04-09 15:20:10 +08:00
import axios from '@/axios';
2023-04-02 23:27:45 +08:00
describe('src/axios.ts', () => {
2023-04-22 16:12:32 +08:00
const data = { 'src/axios.ts': true };
2023-04-02 23:27:45 +08:00
test('应该处理成功和失败', () => {
axios({
2023-04-03 21:03:33 +08:00
adapter: mockAdapter({
2023-04-02 23:27:45 +08:00
headers: { type: 'json' },
data: { v1: 1 },
before: (config) => {
expect(config.url).toBe('http://api.com/test/1');
2023-04-02 23:27:45 +08:00
},
}),
baseURL: 'http://api.com',
2023-04-03 21:03:33 +08:00
url: 'test/:id',
2023-04-02 23:27:45 +08:00
params: {
id: 1,
},
2023-04-03 21:03:33 +08:00
}).then((res) => {
expect(res.headers).toEqual({ type: 'json' });
expect(res.data).toEqual({ v1: 1 });
2023-04-02 23:27:45 +08:00
});
2023-04-03 21:03:33 +08:00
axios('test/:id', {
adapter: mockAdapterError({
2023-04-02 23:27:45 +08:00
headers: { type: 'json' },
data: { v1: 1 },
before: (config) => {
2023-04-03 21:03:33 +08:00
expect(config.url).toBe('http://api.com/test/1');
2023-04-02 23:27:45 +08:00
},
}),
baseURL: 'http://api.com',
2023-04-23 23:05:30 +08:00
method: 'post',
2023-04-02 23:27:45 +08:00
data: {
id: 1,
},
2023-04-03 21:03:33 +08:00
}).catch((err) => {
expect(err.response.headers).toEqual({ type: 'json' });
expect(err.response.data).toEqual({ v1: 1 });
2023-04-02 23:27:45 +08:00
});
});
2023-04-22 16:12:32 +08:00
testEachMethods('应该可以发送 %d 请求', (k) => {
const c = {
baseURL: 'http://api.com',
adapter: mockAdapter({
before: (config) => {
expect(config.url).toBe('http://api.com/test');
},
data,
}),
};
axios('test', { ...c, method: k }).then((res) => {
expect(res.data).toEqual(data);
});
axios({ ...c, url: 'test', method: k }).then((res) => {
expect(res.data).toEqual(data);
});
});
2023-04-02 23:27:45 +08:00
});