ravi tandon
ravi tandon

Reputation: 453

Mocking using mocha in NodeJs

How can I mock a client and a server in Mocha using NodeJs. Specifically, I have the following code:

app.post ('path name', function (req, res) { 
  // Some Action 
  res.send(response); 
});

I want to mock the req, res parameters and test res (status, header, message).

Upvotes: 28

Views: 49514

Answers (3)

ravi tandon
ravi tandon

Reputation: 453

I found Node-Fakeweb useful

var request = require('request'); 
  // Mocking a client request 
  request.get({ uri: 'URI', body: 'body' }, function (err, resp, body) {
    // Some Action
  });
}); 

Upvotes: 4

sam100rav
sam100rav

Reputation: 3783

You can use mocha with supertest to mock a request. Here is a wonderful tutorial about how to do it: http://thewayofcode.wordpress.com/2013/04/21/how-to-build-and-test-rest-api-with-nodejs-express-mocha/

Upvotes: 1

Peter Lyons
Peter Lyons

Reputation: 145994

Mocha itself doesn't provide mock/stub/spy type functionality. Sinon is a popular library that does. The home page includes examples of testing ajax as well as their Fake XMLHTTPRequest object.

Upvotes: 28

Related Questions