关于javascript:使用supertest测试下载是否成功

Testing if download is successful with supertest

我正在用supertest测试我的API端点,并且效果很好,但是我不知道如何测试文件下载是否成功。

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

1
app.get('/api/attachment/:id/file', attachment.getFile);

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

1
2
3
4
5
6
7
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);
        }

然后,在测试文件中,尝试以下操作:

1
2
3
4
5
6
7
8
9
10
11
12
13
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();
        });
    });
});

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

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

有人知道怎么做吗?


该问题已在库中解决,或者代码的其他部分存在错误。 您的示例运行良好,并给出

1
2
3
  when trying to download file
File found!
    ? should respond with"200 OK"