Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to use sinon for stubing in mocha node.js?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 605
    Comment on it

    Installation:

     

    1. npm install sinon

     

    It is simple and easy to use. You can easily fake any interface using sinon. Here, I am going to tell how to use sinon to make a stub of any ORM provided method in node.js.

    Sample code:

    1. const sinon = require('sinon');
    2. const expect = require('unexpected');
    3. const Chance = require('chance');
    4.  
    5. const chance = new Chance();
    6.  
    7. describe('claim route', () => {
    8.  
    9. const baseUrl = '/api/v1/claim';
    10. const middleware = server(0, true);
    11. let token = null;
    12.  
    13. beforeEach(cb => {
    14. /** @ignore **/
    15. function authenticated(authenticatedToken) {
    16. token = authenticatedToken;
    17. cb();
    18. }
    19.  
    20. ampsInitialize(() => {
    21. middlewareHelpers.beforeEach(middleware, 'jcowgar', authenticated);
    22. });
    23. });
    24.  
    25. afterEach(() => {
    26. middlewareHelpers.afterEach();
    27. });
    28.  
    29.  
    30. describe('insert', () => {
    31. const insertUrl = `${baseUrl}/add-claim`;
    32.  
    33.  
    34. it('creates a new claim successfully.', cb => {
    35. sinon.stub(Claim, 'insertAndFetch', insertImpl);
    36.  
    37. const data = {
    38. clientId: 192,
    39. groupAbbreviation: 'WEL0065'
    40. };
    41. request(middleware)
    42. .post(insertUrl)
    43. .send(data)
    44. .set('Accept', 'application/json')
    45. .set('Authorization', `Bearer ${token}`)
    46. .expect(httpConstants.STATUS_CREATED_201)
    47. .end((err, res) => {
    48. Claim.insertAndFetch.restore();
    49. if (err) {
    50. cb(err);
    51. } else {
    52. expect(res.status, 'to equal', httpConstants.STATUS_CREATED_201);
    53. cb();
    54. }
    55. });
    56. });
    57.  
    58. });
    59. });

     

    As, I am using objection.js ORM of node so my save() method is insertAndFetch() for me, I have stubbed insertAndFetch() method for my test case.

     

    It will not make a call to db to create a record instead it will invoke my stubbed method.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Reset Password
Fill out the form below and reset your password: