I’ve been writing tests for my loopback backend using loopback-testing project. The backend has set loopback-component-storage in order to provide apis to store files in the filesystem. I want to test file upload using the remote api that loopback-component-storage provides using something like this:
describe('Containers', function() {
lt.it.shouldBeAllowedWhenCalledByUserWithRole(TEST_USER, someRole,
'POST', '/api/containers/somecontainer/upload', somefile);
});
But with no luck... There's no documentation about this. I don't know if it is even possible to test. Any ideas?
Thanks in advance
Some links:
loopback-testing is currently deprecated.
You should consider using supertest instead. It relies on superagent, and allows you to perform http requests on your REST api and assert on response objects.
Then, you can use the attach
method of super-agent to build a multipart-form-data request that can contain a file.
Code using mocha for describing test looks then like this:
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();
});
});
};