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
    • 577
    Comment on it

    Installation:

     

    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:

    const sinon = require('sinon');
    const expect = require('unexpected');
    const Chance = require('chance');
    
    const chance = new Chance();
    
    describe('claim route', () => {
    
        const baseUrl = '/api/v1/claim';
        const middleware = server(0, true);
        let token = null;
    
        beforeEach(cb => {
            /** @ignore **/
            function authenticated(authenticatedToken) {
                token = authenticatedToken;
                cb();
            }
    
            ampsInitialize(() => {
                middlewareHelpers.beforeEach(middleware, 'jcowgar', authenticated);
            });
        });
    
        afterEach(() => {
            middlewareHelpers.afterEach();
        });
    
    
        describe('insert', () => {
            const insertUrl = `${baseUrl}/add-claim`;
    
    
            it('creates a new claim successfully.', cb => {
                sinon.stub(Claim, 'insertAndFetch', insertImpl);
    
                const data = {
                    clientId: 192,
                    groupAbbreviation: 'WEL0065'
                };
                request(middleware)
                    .post(insertUrl)
                    .send(data)
                    .set('Accept', 'application/json')
                    .set('Authorization', `Bearer ${token}`)
                    .expect(httpConstants.STATUS_CREATED_201)
                    .end((err, res) => {
                        Claim.insertAndFetch.restore();
                        if (err) {
                            cb(err);
                        } else {
                            expect(res.status, 'to equal', httpConstants.STATUS_CREATED_201);
                            cb();
                        }
                    });
            });
    
        });
    });

     

    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
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: