简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM