使用supertest测试下载是否成功

Mar*_*lén 15 javascript mocha.js node.js express supertest

我正在使用supertest测试我的API端点,它工作得很好,但我无法弄清楚如何测试文件下载是否成功.

在我的路由文件中,我已将端点定义为:

app.get('/api/attachment/:id/file', attachment.getFile);
Run Code Online (Sandbox Code Playgroud)

并且函数getFile()看起来像这样:

exports.getFile = function(req, res, next) {
    Attachment.getById(req.params.id, function(err, att) {
        [...]
        if (att) {
            console.log('File found!');
            return res.download(att.getPath(), att.name);
        }
Run Code Online (Sandbox Code Playgroud)

然后,在我的测试文件中,我尝试以下方法:

describe('when trying to download file', function() {
    it('should respond with "200 OK"', function(done) {
        request(url)
        .get('/api/attachment/' + attachment._id + '/file');
        .expect(200)
        .end(function(err, res) {
            if (err) {
                return done(err);
            }
            return done();
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

我确定找到了该文件,因为它已注销File found!.如果我手动尝试它也可以正常工作,但由于某种原因,mocha返回Error: expected 200 "OK", got 404 "Not Found".

我尝试过不同的mime-types和supertest .set("Accept-Encoding": "*"),但没有任何效果.

有人知道怎么做吗?

bol*_*lav 3

问题要么已在库中得到解决,要么代码的其他部分存在错误。你的例子运行良好,并给出

\n\n
  when trying to download file\nFile found!\n    \xe2\x9c\x93 should respond with "200 OK"\n
Run Code Online (Sandbox Code Playgroud)\n