Sawyer
Sawyer

Reputation: 443

Mock a node.js API call using sinon

I have an api in index.js which does a post request. The method which does the channel subscription is subscribeToChannel. I would like to know some hint. I am new to nodejs and I am feeling a bit tough to mock/stub objects using sinon. Mockito for java was easier. I am using mocha, chai but none of them I feel is comfartable and feel very very trickey may be because of less exposure of Nodejs.

The below API doesnt even have a module.exports=server variable inorder to inject or call the method. How do I mock the methods of below file. Reply will be appreciated.

Upvotes: 1

Views: 1293

Answers (1)

danday74
danday74

Reputation: 56986

To mock the response of an API call you use nock:

https://www.npmjs.com/package/nock

You use it inside your mocha chai unit tests.

Basically with nock you say ... when a POST is made to /my/endpoint THEN respond with ... your mock response

Hopefully this is what you need.

Alternatively, if you don't need to mock an HTTP request but a node JS library then you can wrap that library in your own code and then mock your wrapper methods.

Upvotes: 2

Related Questions