我正在尝试使用mocha -enzyme nock对axios.get进行单元测试,其中响应的类型为数组缓冲区。测试在本地通过,但在詹金斯失败。可能是什么原因?
我尝试增加get请求的超时时间,但它成功了。
axios请求如下:
axios.get(url, {
responseType: 'arraybuffer'
})
.then((response) => {
const fileData = {
fileContent: Buffer.from(response.data || '', 'base64'),
fileHeaders: response.headers
};
return Promise.resolve(fileData);
});
,测试如下:
it('GETs correctly the file content as array buffer and the response headers as fileData object', (done) => {
const fileContent = new Uint8Array(new ArrayBuffer(
[72, 101, 108, 108, 111,0]));
const expectedFileData = {
fileContent: Buffer.from(fileContent, 'base64'),
fileHeaders: {
"content-type": "application/vnd.ms-excel",
"content-disposition": 'form-data; name="file"; filename="report_2019-07-30_2019-08-27.xls"'
}
};
const scope = nock('http://localhost/')
.defaultReplyHeaders({
"content-type": "application/vnd.ms-excel",
"content-disposition": 'form-data; name="file"; filename="report_2019-07-30_2019-08-27.xls"'
})
.get(
'/filedownloadurl/fileId'
)
.reply(201, fileContent);
getBinary(
'http://localhost/filedownloadurl/fileId'
).then((response) => {
setTimeout(() => {
expect(response).toEqual(expectedFileData);
scope.done();
done();
}, 100);
});
});
在这里,如果我记录输出,响应不等于“ expectedFileData”, 但是测试在本地神奇地通过了,在詹金斯失败了。请提出其他测试该代码段的方法,或者任何仅在Jenkins上失败的原因?
答案 0 :(得分:0)
这是解决类似问题的方法:使用带有axios,jest和nock的二进制数据构建测试。我从存储在测试文件夹中的zip文件中读取二进制数据。
import Axios from 'axios';
import nock from 'nock';
import fs from 'fs';
describe('Response binary content', () => {
beforeAll(() => {
nock('https://www.test.com')
.get('/binary')
.reply(200, fs.readFileSync(`${__dirname}/data/binary.zip`, 'binary'), {
'content-type': 'application/octet-stream',
'content-length': '16563',
'content-disposition': 'attachment; filename=binary.zip',
});
});
it('should handle binary files', async () => {
const download = await Axios({
method: 'get',
url: 'https://www.test.com/binary',
responseType: 'arraybuffer',
});
expect(download).toBeDefined();
expect(download.headers['content-type']).toEqual(
'application/octet-stream',
);
expect(download.headers['content-length']).toEqual('16563');
});
});