1
我被困在我的一个测试中。在我的测试中,我需要检测客户端(浏览器)是否取消或中止了图片上传。我的问题是如何模拟连接何时中止。在我的控制器中,我可以模拟连接丢失,并且我的代码正确反应。但正如我所提到的问题仍然是如何从测试中触发。 我使用摩卡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。油门模拟慢速上传,并在超时我触发连接丢失。
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。我怎样才能从测试中触发它?
这是当前的测试,即上传图像,并以Controller为目标。使用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);
多方听取该事件,并做出相应的反应。
我该如何从测试中做到这一点?