Pada artikel sebelumnya saya telah menulis bagaimana membuat REST API di nodejs dengan menggunakan expressjs, kali ini saya akan membuat unit test untuk REST API yang telah kita buat.
Semua code telah tersedia di github saya, disini https://github.com/mazipan/nodejs-simple-restfull-test-with-mocha
Sebelumnya mungkin anda ingin membaca dokumentasinya :
1. Supertest : https://github.com/visionmedia/supertest
2. Mocha : http://mochajs.org/
3. Should : https://shouldjs.github.io/
Berikut adalah contoh unit test yang saya buat, sebagai berikut :
1. Pertama saya mesti membuat package.json sebagai depedency management
{ "name": "nodejs-simple-restfull-test-with-mocha", "version": "0.0.0", "private": true, "scripts": { "start": "node ./bin/www" }, "dependencies": { "body-parser": "^1.13.2", "express": "^4.13.1" }, "devDependencies": { "mocha": "^2.2.5", "should": "^7.0.2", "supertest": "^1.0.1" } }
2. Saya membuat file test dengan nama test.js, berikut contoh satu unit test
var supertest = require("supertest"); var should = require("should"); // This agent refers to PORT where program is runninng. var server = supertest.agent("http://localhost:3000"); var random = Math.random(); var idProduct = ""; // UNIT test begin describe("REST API unit test.",function(){ it("should return all products",function(done){ // Test Get All Products server .get("/api/products") .expect("Content-type",/json/) .expect(200) // This is HTTP response .end(function(err,res){ // HTTP status should be 200 res.status.should.equal(200); // Error key should be false. res.body.result.should.equal(true); done(); }); }); });
Untuk code lengkapnya bisa di cek di github repo saya.
Terima kasih dan semoga bermanfaat.