【发布时间】:2017-07-03 07:36:21
【问题描述】:
我陷入了一项测试。在我的测试中,我需要检测客户端(浏览器)已取消或中止图像上传。我的问题是如何在连接中止时进行模拟。在我的控制器中,可以说模拟了连接丢失,并且我的代码反应正确。但正如我提到的,问题仍然是如何从测试中触发它。 我使用 Mocha 3.2.0 作为测试套件,在控制器端我使用multiparty。
这是原始代码:
return new Promise((resolve, reject) => {
let form = new multiparty.Form();
let fileCount = 0;
form.on('part', function (part) {
fileCount++;
let tmpFile = path.join(os.tmpDir(), `${userId}_${timePrefix}_${path.basename(part.filename)}`);
part.pipe(fs.createWriteStream(tmpFile));
part.on('end', () => {
resolve(fs.createReadStream(tmpFile));
});
part.on('error', function (error) {
reject(error);
});
});
form.on('error', (error) => {
reject(new LogicalError(
`Image input request is not valid`, errorCodes.VALIDATION.IMAGE_UPLOAD_DATA_INVALID);
});
form.parse(request);
}).then((imageStream) => {
//AWS S3 is hendled here...
现在我添加了一个新案例,在该案例中我触发了客户端连接被取消。我用过Throttle。 Throttle 模拟慢速上传,超时触发连接丢失。
return new Promise((resolve, reject) => {
let form = new multiparty.Form();
let fileCount = 0;
let throttle = new Throttle(1); //1 = 1 byte. 1000 = 1kb... all per second
form.on('part', function (part) {
fileCount++;
let tmpFile = path.join(os.tmpDir(), `${userId}_${timePrefix}_${path.basename(part.filename)}`);
//part.pipe(fs.createWriteStream(tmpFile));
//Slows down the upload
part.pipe(throttle).pipe(fs.createWriteStream(tmpFile));
//trigger connection aborted
setTimeout(function () {
request.emit('aborted');
},10);
part.on('end', () => {
resolve(fs.createReadStream(tmpFile));
});
part.on('error', function (error) {
reject(error);
});
});
form.on('error', (error) => {
let err = null;
if (error.message.includes('Request aborted')){
err = new LogicalError(
`Client aborted image upload process`, errorCodes.VALIDATION.IMAGE_UPLOAD_CLIENT_REQUEST_ABORTED);
} else {
err = new LogicalError(
`Image input request is not valid`, errorCodes.VALIDATION.IMAGE_UPLOAD_DATA_INVALID);
}
reject(err);
});
form.parse(request);
}).then((imageStream) => {
//AWS S3 is hendled here...
此模拟按预期工作。代码识别适当的条件(请求中止)。 当然,我不能离开这个节流阀和 setTimeout。如何从测试中触发它?
这是当前的测试,即上传图片,以控制器为目标。使用supertest:
describe('ImageControllerTest', function () {
it('should upload image with name for the given user', (done) => {
request(app)
.put('path-to-controller/test-image.jpg')
.attach('file', imagePath.testImagePath)
.set(cons.TOKEN.HEADERS)
.expect((res) => {
//series of expect statements.
})
.expect(200, done);
});
});
在我的第二次尝试中(代码在上面),我通过这样做模拟了连接中止:
setTimeout(function () {
request.emit('aborted');
},10);
多方侦听该事件并做出相应反应。
我怎样才能从测试中做到这一点?
【问题讨论】:
标签: javascript node.js file-upload mocha.js supertest