Using chai

We also need to make a little change to our microservice. We need to export its app so that the HTTP plugin from chai can load it and were able to test it without the need to run in a separate console. Add this to the end of our microservice file:

module.exports = app;

You should have a folder hierarchy similar to the following screenshot:

We should now change our image-upload.js test file to create our first real test:

const chai  = require("chai");
const http = require("chai-http");
const tools = require("../tools");

chai.use(http);

describe("Uploading image", () => {
beforeEach((done) => {
chai
.request(tools.service)
.delete("/uploads/test_image_upload.png")
.end(() => {
return done();
});
});

it ("should accept a PNG image", function (done) {
chai
.request(tools.service)
.post("/uploads/test_image_upload.png")
.set("Content-Type", "image/png")
.send(tools.sample)
.end((err, res) => {
chai.expect(res).to.have.status(200);
chai.expect(res.body).to.have.status("ok");

return done();
});
});
});

We start by first including the chai modules and our tools file:

const chai  = require("chai");
const http = require("chai-http");
const tools = require("../tools");

chai.use(http);

Then, we describe our test file as Uploading image:

describe("Uploading image", () => {

We'll add the different use cases we can think of, related to the uploading of images.

Inside, we use beforeEach, which is a mocha method that will be called before every test in this file. Remember, we want our tests to be consistent, so we add this method to remove our image before running every test. We don't care whether the image exists:

beforeEach((done) => {
chai
.request(tools.service)
.delete("/uploads/test_image_upload.png")
.end(() => {
return done();
});
});

Look how we use the tools.service, which points to our microservice. If, later on, we change the name or somehow make it more complex, we just need to change the tools file, and everything should work.

Then, we add our first integration file's test – a simple image upload:

it("should accept a PNG image", (done) => {
chai
.request(tools.service)
.post("/uploads/test_image_upload.png")
.set("Content-Type", "image/png")
.send(tools.sample)
.end((err, res) => {
chai.expect(res).to.have.status(200);
chai.expect(res.body).to.have.status("ok");

return done();
});
});

It checks whether the HTTP response code is 200 and if the response body, which is a JSON structure, has the status property set to ok. And we're done!

Let's run our test suite again and see how it goes.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset