环回测试上传文件作为具有角色的用户

Loopback testing upload file as a user with role

我一直在使用环回测试项目为我的环回后端编写测试。 后端已设置 loopback-component-storage 以提供 apis 来将文件存储在文件系统中。我想使用 loopback-component-storage 提供的远程 api 来测试文件上传:

describe('Containers', function() {
   lt.it.shouldBeAllowedWhenCalledByUserWithRole(TEST_USER, someRole, 
      'POST', '/api/containers/somecontainer/upload', somefile);
});

但运气不好……没有关于此的文档。我什至不知道是否有可能进行测试。有什么想法吗?

提前致谢

部分链接:

https://github.com/strongloop/loopback-testing

https://github.com/strongloop/loopback-component-storage

loopback-testing is currently deprecated.

您应该考虑使用 supertest instead. It relies on superagent,并允许您对 REST api 执行 http 请求并对响应对象断言。

然后,您可以使用 attach method of super-agent 构建一个可以包含文件的 multipart-form-data 请求。

使用 mocha 描述测试的代码如下所示:

var request = require('supertest');
var fs = require('fs');
var app = require('./setup-test-server-for-test.js');

function json(verb, url) {
    return request(app)[verb](url)
    .set('Content-Type', 'multipart/form-data');
};

describe("User",function() {
    it("should be able to add an asset to the new project", function(done){
       var req = json('post', '/api/containers/someContainer/upload?access_token=' + accessToken)
       .attach("testfile","path/to/your/file.jpg")
       .expect(200)
       .end(function(err, res){
            if (err) return done(err);
            done();
       });
    });

    it("should have uploaded the new asset to the project folder", function(done){
        fs.access('/path/to/your/file.jpg', fs.F_OK, function(err){
            if (err) return done(err);
            done();
        });
    });
};