In this lesson, we'll use Chai's request method to test our Node application ' s API responses.
By the end of this lesson, you'll know how to:
-Install the prerequisites to use mocha and chai in your application
-Test for HTTP status response codes
-Test for a string of text on a page
-Test for a JSON response and validate the properties of the object
-Write tests that is verify the response of your application, but the behavior as well
Const Mockrouter = require ('./routes/mock '); App.use ('/mock ', mockrouter);
//Routers/mock.jsConst Express= Require (' Express '); Const router=Express. Router (); Router. Get ('/', (req, res, next) ={res.status (200). JSON ({title:' Mock test '}). Post ('/', (req, res, next) ={const {v1, V2}=Req.body; if(IsNaN (number (v1)) | |IsNaN (Number (v2))) {Res.status (400). JSON ({' msg ': ' You should provide numbers ' }); } Else{Const result= Number (v1) +Number (v2); Res.status (200). JSON ({result}); }}); Module.exports= Router;
//Test/mock_test.jsConst CHAI= Require (' Chai '); Const Chaihttp= Require (' Chai-http '); const should=chai.should (); Const server= require ('.. /.. /src/app '); Chai.use (chaihttp);d Escribe ('/mock GET ', () ={It (' Should return JSON ', (done) ={chai.request (server). Get ('/mock '). End ((err, res)={res.should.have.status (200); Res.body.should.have.property (' Title '). and. That. Equal (' Mock test '); Done (); }) }); It (' should return right value ', (done) ={chai.request (server). Post ('/mock '). Set (' Content-type ', ' Application/json '). Send ({v1:2, V2:3}). End ((err, res)={res.should.have.status (200); Res.body.should.have.property (' Result '). That.equals (5); Done (); }); }); It (' should return to error ', (done) ={chai.request (server). Post ('/mock '). Set (' Content-type ', ' Application/json '). Send ({v1:' Tow ', V2:' Three '}). End ((err, res)={res.should.have.status (400); Res.body.should.have.property (' msg '). That.contains (' Provide numbers '); Done (); }); });});
[node. js] Test Node RESTful API with Mocha and Chai