Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test with a file upload in mocha

I have an app built on Express.js and I'd like to test the file upload functionality. I'm trying to reproduce the object parsed to req.files (when using express.bodyParser middleware). How can I do this?

like image 370
Mark Nguyen Avatar asked Apr 12 '12 09:04

Mark Nguyen


People also ask

What is beforeEach in Mocha?

Before is before the whole block, beforeEach is before each test. – Steven Scott. Sep 18, 2015 at 21:35.

What is SuperTest in Mocha?

SuperTest is a Node. js library that helps developers test APIs. It extends another library called superagent, a JavaScript HTTP client for Node. js and the browser. Developers can use SuperTest as a standalone library or with JavaScript testing frameworks like Mocha or Jest.


1 Answers

Here is an example of how you would do it with supertest module.

var should = require('should'),     supertest = require('supertest'); var request = supertest('localhost:3000');  describe('upload', function() {     it('a file', function(done) {        request.post('/your/endpoint')               .field('extra_info', '{"in":"case you want to send json along with your file"}')               .attach('image', 'path/to/file.jpg')               .end(function(err, res) {                   res.should.have.status(200); // 'success' status                   done();               });     }); }); 
like image 109
Jack Avatar answered Oct 02 '22 21:10

Jack