Write tests for file upload using mocha

Ibrahim Mohammed
2 min readJan 22, 2020

--

mocha image copied from Google
copied from Google

Writing tests is essential when creating Apis. It allows you to detect bugs and be sure if your functions are working as they should.

Here is a good explanation on writing file upload test by Franklin Ikenna Isaiha. In that article he used file system which worked perfectly. But using the file system, your test passes locally and not on Travis.

I reached out to him and he gave me a hint on how to successfully write file upload tests that will pass locally and on Travis.

Prerequisites

  1. installed all necessary dependencies for your node js project.
  2. install mocha and chai and chai-http.
  3. you must have your file upload controller working (if you choose to do that before writing tests).

Testing

In your test folder, create a folder and add a file or image as the case maybe (what you are testing).

import chai from 'chai';import chaiHttp from 'chai-http';import path from 'path';
//depending on your file structure import app from '../server';chai.use(chaiHttp);chai.should();describe('file upload', () => {it('should post a gif', (done) => {chai.request(app).post('/api/v1/gifs').attach('gif', path.join(__dirname, './test-images/gif.gif'), 'gif.gif').field('gifTitle', 'my gif').end((err, res) => {res.should.have.status(201);res.body.should.be.a('object');})done();})})

By using path, you make the file available locally and also online. This makes it possible for Travis to pick up the file when running.

.attach() takes in three parameters, the key, the file path and the filename which is the value and the file name..field() serves at the input field.

Conclusion

Hopefully this article is well explanatory for you to also write your file upload tests.

Let me know what you think about the article in the comments.

--

--

No responses yet