我在React应用程序中使用围绕Axios的自定义API客户端包装,而我对如何测试用于正确下载文件的功能一无所知。测试get
和post
方法都没有问题,但是postForFile
确实让我感到困惑。
apiClient.js
import axios from 'axios';
const getData = response => response.data;
export default class apiClient {
constructor(baseURL) {
this.axios = axios.create({ baseURL });
}
get = (url, ...args) => this.axios.get(url, ...args).then(getData);
post = (url, data) => this.axios.post(url, data).then(getData);
postForFile = (url, data, mimeType, fileName) =>
this.axios.post(url, data, { responseType: 'arraybuffer' }).then(response => {
const a = document.createElement('a');
mimeType = mimeType || 'application/octet-stream';
if (navigator.msSaveBlob) {
// IE10
navigator.msSaveBlob(
new Blob([response.data], {
type: mimeType
}),
fileName
);
} else if (URL && 'download' in a) {
// html5 A[download]
a.href = URL.createObjectURL(
new Blob([response.data], {
type: mimeType
})
);
a.setAttribute('download', fileName);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
} else {
// eslint-disable-next-line no-restricted-globals
location.href = `data:application/octet-stream,${encodeURIComponent(response.data)}`;
}
});
}
apiClient.test.js
import ApiClient from '../apiClient';
describe('ApiClient', () => {
const apiClient = new ApiClient('http://localhost:8080');
it('calls GET mocked axios via ApiClient and returns data', () => {
apiClient.get('common/AppData').then(result => {
expect(result).toEqual('get completed');
});
});
it('calls POST mocked axios via ApiClient and returns data', () => {
apiClient.post('common/AppData', { test: true }).then(result => {
expect(result).toEqual('post completed');
});
});
it('calls POST (for file) mocked axios via ApiClient and returns data', () => {
apiClient.postForFile('common/FileData', { test: true }, 'applicaton/pdf', 'TestFile.pdf').then(result => {
// ?
});
})
});
最后,我的模拟文件:
axios.js
export default {
create: jest.fn(() => ({
get: jest.fn(() => Promise.resolve({ data: 'get completed' })),
post: jest.fn(() => Promise.resolve({ data: 'post completed' }))
}))
};
任何想法都将不胜感激。
谢谢!