Write tests for file upload using mocha

Write tests for file upload using mocha

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

Here is a good explanation of the writing file upload test by Franklin Ikenna Isaiha. In that article, he used a 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

  • Installed all necessary dependencies for your node js project.

  • Install mocha and chai and chai-http.

  • 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 may be.

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 as the input field.

Conclusion

I'm confident that this article provides a clear explanation for you to successfully create your file upload tests.