如何模拟客户端中止

我被困在我的一个testing中。 在我的testing中,我需要检测客户端(浏览器)已经取消或中止图片上传。 我的问题是如何模拟连接中止的时间。 在我的控制器中,我可以模拟连接丢失,并且我的代码正确地反应。 但正如我所提到的问题仍然是如何从testing中触发。 我使用摩卡3.2.0作为testing套件,而在控制器端我使用多方 。

这是原始的代码:

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... 

现在我添加了一个新的案例,我触发客户端连接被取消。 我已经使用了节气门 。 油门模拟慢速上传,并在超时我触发连接丢失。

 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。 我怎样才能从testing中触发它?

这是目前的testing,即上传图像,并针对控制器。 使用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); 

多方监听该事件,并作出相应的反应。

我如何从testing中做到这一点?

简单的方法可以是 – 在subprocess中创build客户端使用:

 const fork = require('child_process').fork; const path = require('path'); const child = fork(path.join(__dirname, './some-sub.js')); 

而当你需要触发取消 – 只需closures进程:

 child.close(); 

或者从stream程本身:

 process.exit(0);