我使用Chakram(它基于Mocha)和NodeJS测试API。这是测试代码(我测试一个WebService,它获取文件和一些数据,然后将其上传到FTP服务器):
let chakram = require('chakram'),
expect = chakram.expect,
wait = chakram.wait;
let fs = require('fs')
let path = require("path");
let g = require('./lib/globals.js'); /* I define some globals, like g.portfolioUrl: the WebService url I'll test */
let assert = require('assert');
...
it("should put a file in root folder", function () {
let $body = {
action: 'putFile',
parentPath: '/',
filenameToStore: 'sample_picture.png'
};
/* "options['headers']" is already defined and a "before" step adds authentication cookie */
options['headers']['Content-Type'] = 'multipart/form-data; charset=utf-8; boundary='
+ Math.random().toString().substr(2);
options['formData'] = {
pkgFile: fs.createReadStream(path.resolve(__dirname, '../test/res/sample_picture.png'))
};
return chakram.post(g.portfolioUrl, $body, options).then(function (response) {
expect(response).to.have.status(200);
return response;
});
});
我收到此错误(似乎与fs.createReadStream有关):
Error:
write after end
at write_ (_http_outgoing.js:635:15)
at ClientRequest.write (_http_outgoing.js:630:10)
at Request.write (D:\wamp64\www\***\test\***\node_modules\request\request.js:1514:27)
at FormData.ondata (internal/streams/legacy.js:16:26)
at emitOne (events.js:115:13)
at FormData.emit (events.js:210:7)
at FormData.CombinedStream.write (D:\wamp64\www\***\test\***\node_modules\combined-stream\lib\combined_stream.js:118:8)
at DelayedStream.ondata (internal/streams/legacy.js:16:26)
at emitOne (events.js:115:13)
at DelayedStream.emit (events.js:210:7)
at DelayedStream._handleEmit (D:\wamp64\www\***\test\***\node_modules\delayed-stream\lib\delayed_stream.js:82:15)
at ReadStream.source.emit (D:\wamp64\www\***\test\***\node_modules\delayed-stream\lib\delayed_stream.js:29:19)
at addChunk (_stream_readable.js:252:12)
at readableAddChunk (_stream_readable.js:239:11)
at ReadStream.Readable.push (_stream_readable.js:197:10)
at onread (fs.js:2004:12)
at FSReqWrap.wrapper [as oncomplete] (fs.js:663:17) {stack: Error: write after end
at write_ (_http_outgoi… FSReqWrap.wrapper [as oncomplete] (fs.js:663:17),
message: write after end}
使用NodeJS 6.11.0和8.1.3在Windows10上测试。
我找到了一些可能的Mocha解决方案(参见How to unit test with a file upload in mocha),但我不知道如何让它适应Chakram。
答案 0 :(得分:0)
Chakram包含一个等待请求完成的方法。
https://github.com/dareid/chakram#waiting
你可以这样试试:
...
const TaskService = require('./TaskService);
...
TaskController.delete = function(req, res) {
if (!req.params.id) {
res.json({ message: 'Please provide a task to delete.' });
} else {
TaskService.delete();
}
}