2
0
mirror of https://github.com/tenrok/axios.git synced 2026-06-20 20:00:40 +03:00

Fix/typescript tests (#5375)

* chore(ci): Add release-it script;

* chore(ci): add `release:no-npm` script to release the package without making an npm release;

* fix(test): fixed `d.ts` typings;
refactor(test): refactor typescript tests;
This commit is contained in:
Dmitriy Mozgovoy
2022-12-14 22:49:49 +02:00
committed by GitHub
parent f2547d0e03
commit 7a2f901f42
11 changed files with 308 additions and 149 deletions
+2 -3
View File
@@ -3,10 +3,9 @@
.tscache .tscache
.DS_Store .DS_Store
node_modules/ node_modules/
typings/
coverage/ coverage/
test/typescript/axios.js* test/typescript/axios.js*
sauce_connect.log sauce_connect.log
test/module/cjs/node_modules/ test/module/**/package-lock.json
test/module/cjs/package-lock.json
backup/ backup/
./.husky/
+20 -12
View File
@@ -18,16 +18,9 @@ type AxiosHeaderGetter = ((parser?: RegExp) => RegExpExecArray | null) |
type AxiosHeaderTester = (matcher?: AxiosHeaderMatcher) => boolean; type AxiosHeaderTester = (matcher?: AxiosHeaderMatcher) => boolean;
type MaxUploadRate = number;
type MaxDownloadRate = number;
type Milliseconds = number;
declare class AxiosHeaders { declare class AxiosHeaders {
constructor( constructor(
headers?: RawAxiosHeaders | AxiosHeaders, headers?: RawAxiosHeaders | AxiosHeaders
defaultHeaders?: RawAxiosHeaders | AxiosHeaders
); );
set(headerName?: string, value?: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; set(headerName?: string, value?: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
@@ -44,12 +37,16 @@ declare class AxiosHeaders {
normalize(format: boolean): AxiosHeaders; normalize(format: boolean): AxiosHeaders;
concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string>): AxiosHeaders;
toJSON(asStrings?: boolean): RawAxiosHeaders; toJSON(asStrings?: boolean): RawAxiosHeaders;
static from(thing?: AxiosHeaders | RawAxiosHeaders | string): AxiosHeaders; static from(thing?: AxiosHeaders | RawAxiosHeaders | string): AxiosHeaders;
static accessor(header: string | string[]): AxiosHeaders; static accessor(header: string | string[]): AxiosHeaders;
static concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string>): AxiosHeaders;
setContentType: AxiosHeaderSetter; setContentType: AxiosHeaderSetter;
getContentType: AxiosHeaderGetter; getContentType: AxiosHeaderGetter;
hasContentType: AxiosHeaderTester; hasContentType: AxiosHeaderTester;
@@ -199,7 +196,7 @@ declare namespace axios {
type RawAxiosRequestHeaders = Partial<RawAxiosHeaders & MethodsHeaders & CommonHeaders>; type RawAxiosRequestHeaders = Partial<RawAxiosHeaders & MethodsHeaders & CommonHeaders>;
type AxiosRequestHeaders = Partial<RawAxiosHeaders & MethodsHeaders & CommonHeaders> & AxiosHeaders; type AxiosRequestHeaders = RawAxiosRequestHeaders & AxiosHeaders;
type RawAxiosResponseHeaders = Partial<Record<string, string> & { type RawAxiosResponseHeaders = Partial<Record<string, string> & {
"set-cookie"?: string[] "set-cookie"?: string[]
@@ -321,6 +318,10 @@ declare namespace axios {
serialize?: CustomParamsSerializer; serialize?: CustomParamsSerializer;
} }
type MaxUploadRate = number;
type MaxDownloadRate = number;
type BrowserProgressEvent = any; type BrowserProgressEvent = any;
interface AxiosProgressEvent { interface AxiosProgressEvent {
@@ -335,20 +336,26 @@ declare namespace axios {
event?: BrowserProgressEvent; event?: BrowserProgressEvent;
} }
type Milliseconds = number;
type AxiosAdapterName = 'xhr' | 'http' | string;
type AxiosAdapterConfig = AxiosAdapter | AxiosAdapterName;
interface AxiosRequestConfig<D = any> { interface AxiosRequestConfig<D = any> {
url?: string; url?: string;
method?: Method | string; method?: Method | string;
baseURL?: string; baseURL?: string;
transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[]; transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];
transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[]; transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];
headers?: RawAxiosRequestHeaders; headers?: RawAxiosRequestHeaders | AxiosHeaders;
params?: any; params?: any;
paramsSerializer?: ParamsSerializerOptions; paramsSerializer?: ParamsSerializerOptions;
data?: D; data?: D;
timeout?: Milliseconds; timeout?: Milliseconds;
timeoutErrorMessage?: string; timeoutErrorMessage?: string;
withCredentials?: boolean; withCredentials?: boolean;
adapter?: AxiosAdapter; adapter?: AxiosAdapterConfig | AxiosAdapterConfig[];
auth?: AxiosBasicCredentials; auth?: AxiosBasicCredentials;
responseType?: ResponseType; responseType?: ResponseType;
responseEncoding?: responseEncoding | string; responseEncoding?: responseEncoding | string;
@@ -396,7 +403,7 @@ declare namespace axios {
} }
interface CreateAxiosDefaults<D = any> extends Omit<AxiosRequestConfig<D>, 'headers'> { interface CreateAxiosDefaults<D = any> extends Omit<AxiosRequestConfig<D>, 'headers'> {
headers?: RawAxiosRequestHeaders | Partial<HeadersDefaults>; headers?: RawAxiosRequestHeaders | AxiosHeaders | Partial<HeadersDefaults>;
} }
interface AxiosResponse<T = any, D = any> { interface AxiosResponse<T = any, D = any> {
@@ -485,6 +492,7 @@ declare namespace axios {
isAxiosError<T = any, D = any>(payload: any): payload is AxiosError<T, D>; isAxiosError<T = any, D = any>(payload: any): payload is AxiosError<T, D>;
toFormData(sourceObj: object, targetFormData?: GenericFormData, options?: FormSerializerOptions): GenericFormData; toFormData(sourceObj: object, targetFormData?: GenericFormData, options?: FormSerializerOptions): GenericFormData;
formToJSON(form: GenericFormData|GenericHTMLFormElement): object; formToJSON(form: GenericFormData|GenericHTMLFormElement): object;
AxiosHeaders: typeof AxiosHeaders;
} }
} }
Vendored
+4 -3
View File
@@ -71,7 +71,7 @@ export class AxiosHeaders {
export type RawAxiosRequestHeaders = Partial<RawAxiosHeaders & MethodsHeaders & CommonHeaders>; export type RawAxiosRequestHeaders = Partial<RawAxiosHeaders & MethodsHeaders & CommonHeaders>;
export type AxiosRequestHeaders = Partial<RawAxiosHeaders & MethodsHeaders & CommonHeaders> & AxiosHeaders; export type AxiosRequestHeaders = RawAxiosRequestHeaders & AxiosHeaders;
export type RawAxiosResponseHeaders = Partial<Record<string, string> & { export type RawAxiosResponseHeaders = Partial<Record<string, string> & {
"set-cookie"?: string[] "set-cookie"?: string[]
@@ -289,7 +289,7 @@ export interface AxiosRequestConfig<D = any> {
baseURL?: string; baseURL?: string;
transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[]; transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];
transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[]; transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];
headers?: RawAxiosRequestHeaders; headers?: RawAxiosRequestHeaders | AxiosHeaders;
params?: any; params?: any;
paramsSerializer?: ParamsSerializerOptions; paramsSerializer?: ParamsSerializerOptions;
data?: D; data?: D;
@@ -344,7 +344,7 @@ export interface AxiosDefaults<D = any> extends Omit<AxiosRequestConfig<D>, 'hea
} }
export interface CreateAxiosDefaults<D = any> extends Omit<AxiosRequestConfig<D>, 'headers'> { export interface CreateAxiosDefaults<D = any> extends Omit<AxiosRequestConfig<D>, 'headers'> {
headers?: RawAxiosRequestHeaders | Partial<HeadersDefaults>; headers?: RawAxiosRequestHeaders | AxiosHeaders | Partial<HeadersDefaults>;
} }
export interface AxiosResponse<T = any, D = any> { export interface AxiosResponse<T = any, D = any> {
@@ -499,6 +499,7 @@ export interface AxiosStatic extends AxiosInstance {
CancelToken: CancelTokenStatic; CancelToken: CancelTokenStatic;
Axios: typeof Axios; Axios: typeof Axios;
AxiosError: typeof AxiosError; AxiosError: typeof AxiosError;
HttpStatusCode: typeof HttpStatusCode;
readonly VERSION: string; readonly VERSION: string;
isCancel: typeof isCancel; isCancel: typeof isCancel;
all: typeof all; all: typeof all;
+4 -2
View File
@@ -23,7 +23,7 @@
"type": "module", "type": "module",
"types": "index.d.ts", "types": "index.d.ts",
"scripts": { "scripts": {
"test": "npm run test:eslint && npm run test:mocha && npm run test:karma && npm run test:exports && npm run test:dtslint", "test": "npm run test:eslint && npm run test:mocha && npm run test:karma && npm run test:dtslint && npm run test:exports",
"test:eslint": "node bin/ssl_hotfix.js eslint lib/**/*.js", "test:eslint": "node bin/ssl_hotfix.js eslint lib/**/*.js",
"test:dtslint": "node bin/ssl_hotfix.js dtslint", "test:dtslint": "node bin/ssl_hotfix.js dtslint",
"test:mocha": "node bin/ssl_hotfix.js mocha test/unit/**/*.js --timeout 30000 --exit", "test:mocha": "node bin/ssl_hotfix.js mocha test/unit/**/*.js --timeout 30000 --exit",
@@ -42,9 +42,11 @@
"fix": "eslint --fix lib/**/*.js", "fix": "eslint --fix lib/**/*.js",
"prepare": "husky install && npm run prepare:hooks", "prepare": "husky install && npm run prepare:hooks",
"prepare:hooks": "npx husky add .husky/commit-msg \"npx commitlint --edit $1\"", "prepare:hooks": "npx husky add .husky/commit-msg \"npx commitlint --edit $1\"",
"release:dry": "release-it --dry-run", "release:dry": "release-it --dry-run --no-npm",
"release:info": "release-it --release-version", "release:info": "release-it --release-version",
"prerelease:no-npm": "release-it --preRelease=beta --no-npm",
"prerelease": "release-it --preRelease=beta", "prerelease": "release-it --preRelease=beta",
"release:no-npm": "release-it --no-npm",
"release": "release-it" "release": "release-it"
}, },
"repository": { "repository": {
+46
View File
@@ -14,6 +14,16 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));
const exec = util.promisify(cp.exec); const exec = util.promisify(cp.exec);
const spawn = (command, args) => new Promise((resolve, reject) => {
cp.spawn(command, args, {
shell : true,
stdio: 'inherit'
}).once('error', reject).on(
'close',
(code) => code ? reject(new Error(`Exit code ${code}`)) : resolve()
);
});
const {Axios} = axiosFactory; const {Axios} = axiosFactory;
const ignoreList = ['default']; const ignoreList = ['default'];
@@ -134,4 +144,40 @@ describe('module', function () {
await exec(`npm test --prefix ${pkgPath}`, {}); await exec(`npm test --prefix ${pkgPath}`, {});
}); });
}); });
describe('typings', () => {
describe('ESM', ()=> {
const pkgPath = path.join(__dirname, './typings/esm');
after(async ()=> {
await remove(path.join(pkgPath, './node_modules'));
});
it('should pass types check', async function () {
this.timeout(30000);
await spawn(`npm test --prefix ${pkgPath}`, [], {
shell : true,
stdio: 'pipe'
});
});
});
describe('CommonJS', ()=> {
const pkgPath = path.join(__dirname, './typings/cjs');
after(async ()=> {
await remove(path.join(pkgPath, './node_modules'));
});
it('should pass types check', async function () {
this.timeout(30000);
await spawn(`npm test --prefix ${pkgPath}`, [], {
shell : true,
stdio: 'pipe'
});
});
});
});
}); });
@@ -65,48 +65,48 @@ const handleError = (error: axios.AxiosError) => {
}; };
axios(config) axios(config)
.then(handleResponse) .then(handleResponse)
.catch(handleError); .catch(handleError);
axios.get('/user?id=12345') axios.get('/user?id=12345')
.then(handleResponse) .then(handleResponse)
.catch(handleError); .catch(handleError);
axios.get('/user', { params: { id: 12345 } }) axios.get('/user', { params: { id: 12345 } })
.then(handleResponse) .then(handleResponse)
.catch(handleError); .catch(handleError);
axios.head('/user') axios.head('/user')
.then(handleResponse) .then(handleResponse)
.catch(handleError); .catch(handleError);
axios.options('/user') axios.options('/user')
.then(handleResponse) .then(handleResponse)
.catch(handleError); .catch(handleError);
axios.delete('/user') axios.delete('/user')
.then(handleResponse) .then(handleResponse)
.catch(handleError); .catch(handleError);
axios.post('/user', { foo: 'bar' }) axios.post('/user', { foo: 'bar' })
.then(handleResponse) .then(handleResponse)
.catch(handleError); .catch(handleError);
axios.post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } }) axios.post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } })
.then(handleResponse) .then(handleResponse)
.catch(handleError); .catch(handleError);
axios.put('/user', { foo: 'bar' }) axios.put('/user', { foo: 'bar' })
.then(handleResponse) .then(handleResponse)
.catch(handleError); .catch(handleError);
axios.patch('/user', { foo: 'bar' }) axios.patch('/user', { foo: 'bar' })
.then(handleResponse) .then(handleResponse)
.catch(handleError); .catch(handleError);
// Typed methods // Typed methods
interface UserCreationDef { interface UserCreationDef {
name: string; name: string;
} }
interface User { interface User {
@@ -117,49 +117,49 @@ interface User {
// with default axios.AxiosResponse<T> result // with default axios.AxiosResponse<T> result
const handleUserResponse = (response: axios.AxiosResponse<User>) => { const handleUserResponse = (response: axios.AxiosResponse<User>) => {
console.log(response.data.id); console.log(response.data.id);
console.log(response.data.name); console.log(response.data.name);
console.log(response.status); console.log(response.status);
console.log(response.statusText); console.log(response.statusText);
console.log(response.headers); console.log(response.headers);
console.log(response.config); console.log(response.config);
}; };
axios.get<User>('/user?id=12345') axios.get<User>('/user?id=12345')
.then(handleUserResponse) .then(handleUserResponse)
.catch(handleError); .catch(handleError);
axios.get<User>('/user', { params: { id: 12345 } }) axios.get<User>('/user', { params: { id: 12345 } })
.then(handleUserResponse) .then(handleUserResponse)
.catch(handleError); .catch(handleError);
axios.head<User>('/user') axios.head<User>('/user')
.then(handleUserResponse) .then(handleUserResponse)
.catch(handleError); .catch(handleError);
axios.options<User>('/user') axios.options<User>('/user')
.then(handleUserResponse) .then(handleUserResponse)
.catch(handleError); .catch(handleError);
axios.delete<User>('/user') axios.delete<User>('/user')
.then(handleUserResponse) .then(handleUserResponse)
.catch(handleError); .catch(handleError);
axios.post<User>('/user', { name: 'foo', id: 1 }) axios.post<User>('/user', { name: 'foo', id: 1 })
.then(handleUserResponse) .then(handleUserResponse)
.catch(handleError); .catch(handleError);
axios.post<User>('/user', { name: 'foo', id: 1 }, { headers: { 'X-FOO': 'bar' } }) axios.post<User>('/user', { name: 'foo', id: 1 }, { headers: { 'X-FOO': 'bar' } })
.then(handleUserResponse) .then(handleUserResponse)
.catch(handleError); .catch(handleError);
axios.put<User>('/user', { name: 'foo', id: 1 }) axios.put<User>('/user', { name: 'foo', id: 1 })
.then(handleUserResponse) .then(handleUserResponse)
.catch(handleError); .catch(handleError);
axios.patch<User>('/user', { name: 'foo', id: 1 }) axios.patch<User>('/user', { name: 'foo', id: 1 })
.then(handleUserResponse) .then(handleUserResponse)
.catch(handleError); .catch(handleError);
// (Typed methods) with custom response type // (Typed methods) with custom response type
@@ -168,47 +168,47 @@ const handleStringResponse = (response: string) => {
}; };
axios.get<User, string>('/user?id=12345') axios.get<User, string>('/user?id=12345')
.then(handleStringResponse) .then(handleStringResponse)
.catch(handleError); .catch(handleError);
axios.get<User, string>('/user', { params: { id: 12345 } }) axios.get<User, string>('/user', { params: { id: 12345 } })
.then(handleStringResponse) .then(handleStringResponse)
.catch(handleError); .catch(handleError);
axios.head<User, string>('/user') axios.head<User, string>('/user')
.then(handleStringResponse) .then(handleStringResponse)
.catch(handleError); .catch(handleError);
axios.options<User, string>('/user') axios.options<User, string>('/user')
.then(handleStringResponse) .then(handleStringResponse)
.catch(handleError); .catch(handleError);
axios.delete<User, string>('/user') axios.delete<User, string>('/user')
.then(handleStringResponse) .then(handleStringResponse)
.catch(handleError); .catch(handleError);
axios.post<Partial<UserCreationDef>, string>('/user', { name: 'foo' }) axios.post<Partial<UserCreationDef>, string>('/user', { name: 'foo' })
.then(handleStringResponse) .then(handleStringResponse)
.catch(handleError); .catch(handleError);
axios.post<Partial<UserCreationDef>, string>('/user', { name: 'foo' }, { headers: { 'X-FOO': 'bar' } }) axios.post<Partial<UserCreationDef>, string>('/user', { name: 'foo' }, { headers: { 'X-FOO': 'bar' } })
.then(handleStringResponse) .then(handleStringResponse)
.catch(handleError); .catch(handleError);
axios.put<Partial<UserCreationDef>, string>('/user', { name: 'foo' }) axios.put<Partial<UserCreationDef>, string>('/user', { name: 'foo' })
.then(handleStringResponse) .then(handleStringResponse)
.catch(handleError); .catch(handleError);
axios.patch<Partial<UserCreationDef>, string>('/user', { name: 'foo' }) axios.patch<Partial<UserCreationDef>, string>('/user', { name: 'foo' })
.then(handleStringResponse) .then(handleStringResponse)
.catch(handleError); .catch(handleError);
axios.request<User, string>({ axios.request<User, string>({
method: 'get', method: 'get',
url: '/user?id=12345' url: '/user?id=12345'
}) })
.then(handleStringResponse) .then(handleStringResponse)
.catch(handleError); .catch(handleError);
// Instances // Instances
@@ -216,32 +216,32 @@ const instance1: axios.AxiosInstance = axios.create();
const instance2: axios.AxiosInstance = axios.create(config); const instance2: axios.AxiosInstance = axios.create(config);
instance1(config) instance1(config)
.then(handleResponse) .then(handleResponse)
.catch(handleError); .catch(handleError);
instance1.request(config) instance1.request(config)
.then(handleResponse) .then(handleResponse)
.catch(handleError); .catch(handleError);
instance1.get('/user?id=12345') instance1.get('/user?id=12345')
.then(handleResponse) .then(handleResponse)
.catch(handleError); .catch(handleError);
instance1.options('/user') instance1.options('/user')
.then(handleResponse) .then(handleResponse)
.catch(handleError); .catch(handleError);
instance1.get('/user', { params: { id: 12345 } }) instance1.get('/user', { params: { id: 12345 } })
.then(handleResponse) .then(handleResponse)
.catch(handleError); .catch(handleError);
instance1.post('/user', { foo: 'bar' }) instance1.post('/user', { foo: 'bar' })
.then(handleResponse) .then(handleResponse)
.catch(handleError); .catch(handleError);
instance1.post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } }) instance1.post('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } })
.then(handleResponse) .then(handleResponse)
.catch(handleError); .catch(handleError);
// Defaults // Defaults
@@ -276,41 +276,41 @@ axios.create({
// Interceptors // Interceptors
const requestInterceptorId: number = axios.interceptors.request.use( const requestInterceptorId: number = axios.interceptors.request.use(
(config: axios.AxiosRequestConfig) => config, (config: axios.AxiosRequestConfig) => config,
(error: any) => Promise.reject(error) (error: any) => Promise.reject(error)
); );
axios.interceptors.request.eject(requestInterceptorId); axios.interceptors.request.eject(requestInterceptorId);
axios.interceptors.request.use( axios.interceptors.request.use(
(config: axios.AxiosRequestConfig) => Promise.resolve(config), (config: axios.AxiosRequestConfig) => Promise.resolve(config),
(error: any) => Promise.reject(error) (error: any) => Promise.reject(error)
); );
axios.interceptors.request.use((config: axios.AxiosRequestConfig) => config); axios.interceptors.request.use((config: axios.AxiosRequestConfig) => config);
axios.interceptors.request.use((config: axios.AxiosRequestConfig) => Promise.resolve(config)); axios.interceptors.request.use((config: axios.AxiosRequestConfig) => Promise.resolve(config));
const responseInterceptorId: number = axios.interceptors.response.use( const responseInterceptorId: number = axios.interceptors.response.use(
(response: axios.AxiosResponse) => response, (response: axios.AxiosResponse) => response,
(error: any) => Promise.reject(error) (error: any) => Promise.reject(error)
); );
axios.interceptors.response.eject(responseInterceptorId); axios.interceptors.response.eject(responseInterceptorId);
axios.interceptors.response.use( axios.interceptors.response.use(
(response: axios.AxiosResponse) => Promise.resolve(response), (response: axios.AxiosResponse) => Promise.resolve(response),
(error: any) => Promise.reject(error) (error: any) => Promise.reject(error)
); );
const voidRequestInterceptorId = axios.interceptors.request.use( const voidRequestInterceptorId = axios.interceptors.request.use(
// @ts-expect-error -- Must return an axios.AxiosRequestConfig (or throw) // @ts-expect-error -- Must return an axios.AxiosRequestConfig (or throw)
(_response) => {}, (_response) => {},
(error: any) => Promise.reject(error) (error: any) => Promise.reject(error)
); );
const voidResponseInterceptorId = axios.interceptors.response.use( const voidResponseInterceptorId = axios.interceptors.response.use(
// @ts-expect-error -- Must return an axios.AxiosResponse (or throw) // @ts-expect-error -- Must return an axios.AxiosResponse (or throw)
(_response) => {}, (_response) => {},
(error: any) => Promise.reject(error) (error: any) => Promise.reject(error)
); );
axios.interceptors.request.eject(voidRequestInterceptorId); axios.interceptors.request.eject(voidRequestInterceptorId);
axios.interceptors.response.eject(voidResponseInterceptorId); axios.interceptors.response.eject(voidResponseInterceptorId);
@@ -353,28 +353,28 @@ const fn2: (arr: number[]) => string = axios.spread(fn1);
// Promises // Promises
axios.get('/user') axios.get('/user')
.then((response: axios.AxiosResponse) => 'foo') .then((response: axios.AxiosResponse) => 'foo')
.then((value: string) => {}); .then((value: string) => {});
axios.get('/user') axios.get('/user')
.then((response: axios.AxiosResponse) => Promise.resolve('foo')) .then((response: axios.AxiosResponse) => Promise.resolve('foo'))
.then((value: string) => {}); .then((value: string) => {});
axios.get('/user') axios.get('/user')
.then((response: axios.AxiosResponse) => 'foo', (error: any) => 'bar') .then((response: axios.AxiosResponse) => 'foo', (error: any) => 'bar')
.then((value: string) => {}); .then((value: string) => {});
axios.get('/user') axios.get('/user')
.then((response: axios.AxiosResponse) => 'foo', (error: any) => 123) .then((response: axios.AxiosResponse) => 'foo', (error: any) => 123)
.then((value: string | number) => {}); .then((value: string | number) => {});
axios.get('/user') axios.get('/user')
.catch((error: any) => 'foo') .catch((error: any) => 'foo')
.then((value) => {}); .then((value) => {});
axios.get('/user') axios.get('/user')
.catch((error: any) => Promise.resolve('foo')) .catch((error: any) => Promise.resolve('foo'))
.then((value) => {}); .then((value) => {});
// axios.Cancellation // axios.Cancellation
@@ -394,11 +394,11 @@ source.cancel('Operation has been axios.Canceled.');
// axios.AxiosError // axios.AxiosError
axios.get('/user') axios.get('/user')
.catch((error) => { .catch((error) => {
if (axios.isAxiosError(error)) { if (axios.isAxiosError(error)) {
const axiosError: axios.AxiosError = error; const axiosError: axios.AxiosError = error;
} }
}); });
// FormData // FormData
@@ -411,14 +411,14 @@ axios.get('/user', {signal: new AbortController().signal});
// AxiosHeaders methods // AxiosHeaders methods
axios.get('/user', { axios.get('/user', {
transformRequest: (data, headers) => { transformRequest: (data, headers) => {
headers.setContentType('text/plain'); headers.setContentType('text/plain');
headers['Foo'] = 'bar'; headers['Foo'] = 'bar';
}, },
transformResponse: (data, headers) => { transformResponse: (data, headers) => {
headers.has('foo'); headers.has('foo');
} }
}); });
// Max Rate // Max Rate
@@ -434,7 +434,7 @@ axios.get('/user', {
// Node progress // Node progress
axios.get('/user', { axios.get('/user', {
onUploadProgress: (e) => { onUploadProgress: (e: axios.AxiosProgressEvent) => {
console.log(e.loaded); console.log(e.loaded);
console.log(e.total); console.log(e.total);
console.log(e.progress); console.log(e.progress);
+20
View File
@@ -0,0 +1,20 @@
{
"name": "commonjs-typings-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "npm i --no-save --no-package-lock && tsc -v && npm run test:types",
"test:types": "tsc --noEmit"
},
"keywords": [],
"author": "",
"license": "MIT",
"dependencies": {
"@types/node": "^18.11.3",
"axios": "file:../../../.."
},
"devDependencies": {
"typescript": "^4.9.4"
}
}
+6
View File
@@ -0,0 +1,6 @@
{
"compilerOptions": {
"checkJs": true,
"module": "node16"
}
}
@@ -1,5 +1,9 @@
import axios, { import axios, {
AxiosRequestConfig, AxiosRequestConfig,
AxiosHeaders,
AxiosRequestHeaders,
AxiosResponseHeaders,
RawAxiosRequestHeaders,
AxiosResponse, AxiosResponse,
AxiosError, AxiosError,
AxiosInstance, AxiosInstance,
@@ -293,8 +297,14 @@ axios.create({
// Interceptors // Interceptors
const requestInterceptorId: number = axios.interceptors.request.use( const requestInterceptorId: number = axios.interceptors.request.use(
(config: AxiosRequestConfig) => config, async (config: AxiosRequestConfig) => {
(error: any) => Promise.reject(error) await axios.get('/foo', {
headers: config.headers
});
return config;
},
(error: any) => Promise.reject(error),
{synchronous: false}
); );
axios.interceptors.request.eject(requestInterceptorId); axios.interceptors.request.eject(requestInterceptorId);
@@ -404,11 +414,11 @@ axios.get('/user')
axios.get('/user') axios.get('/user')
.catch((error: any) => 'foo') .catch((error: any) => 'foo')
.then((value) => {}); .then((value: any) => {});
axios.get('/user') axios.get('/user')
.catch((error: any) => Promise.resolve('foo')) .catch((error: any) => Promise.resolve('foo'))
.then((value) => {}); .then((value: any) => {});
// Cancellation // Cancellation
@@ -434,7 +444,7 @@ source.cancel('Operation has been canceled.');
// AxiosError // AxiosError
axios.get('/user') axios.get('/user')
.catch((error) => { .catch((error: AxiosError) => {
if (axios.isAxiosError(error)) { if (axios.isAxiosError(error)) {
const axiosError: AxiosError = error; const axiosError: AxiosError = error;
} }
@@ -467,16 +477,56 @@ axios.get('/user', {signal: new AbortController().signal});
// AxiosHeaders methods // AxiosHeaders methods
axios.get('/user', { axios.get('/user', {
transformRequest: (data, headers) => { transformRequest: [
headers.setContentType('text/plain'); (data: any, headers) => {
headers['Foo'] = 'bar'; headers.setContentType('text/plain');
return 'baz';
}, },
(data: any, headers) => {
transformResponse: (data, headers) => { headers['foo'] = 'bar';
headers.has('foo'); return 'baz'
} }
],
transformResponse: [(data: any, headers: AxiosResponseHeaders) => {
headers.has('foo');
}]
}); });
// config headers
axios.get('/user', {
headers: new AxiosHeaders({x:1})
});
axios.get('/user', {
headers: {
foo : 1
}
});
// issue #5034
function getRequestConfig1(options: AxiosRequestConfig): AxiosRequestConfig {
return {
...options,
headers: {
...(options.headers as RawAxiosRequestHeaders),
Authorization: `Bearer ...`,
},
};
}
function getRequestConfig2(options: AxiosRequestConfig): AxiosRequestConfig {
return {
...options,
headers: {
...(options.headers as AxiosHeaders).toJSON(),
Authorization: `Bearer ...`,
},
};
}
// Max Rate // Max Rate
axios.get('/user', { axios.get('/user', {
@@ -490,7 +540,7 @@ axios.get('/user', {
// Node progress // Node progress
axios.get('/user', { axios.get('/user', {
onUploadProgress: (e) => { onUploadProgress: (e: AxiosProgressEvent) => {
console.log(e.loaded); console.log(e.loaded);
console.log(e.total); console.log(e.total);
console.log(e.progress); console.log(e.progress);
+21
View File
@@ -0,0 +1,21 @@
{
"name": "esm-typings-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test:types": "tsc --noEmit",
"test": "npm i --no-save --no-package-lock && tsc -v && npm run test:types"
},
"keywords": [],
"author": "",
"license": "MIT",
"dependencies": {
"@types/node": "^18.11.3",
"axios": "file:../../../.."
},
"devDependencies": {
"typescript": "^4.9.4"
}
}
+6
View File
@@ -0,0 +1,6 @@
{
"compilerOptions": {
"checkJs": true,
"module": "node16"
}
}