Search code examples
node.jsmocha.jschaisinonsinon-chai

Stubbing a DB connection line in Mocha/Chai/Sinon


I have the following line in my code which is problematic

TestController.ts

static async getTest(req:any, res:any, next:object) {
    console.log("BEGIN -- TestController.getTest");

    let testid = req.params.testid;
    let query = `SELECT * FROM TEST WHERE TEST_ID = :1`;
    let binds: string[] = [testid];

    let result = await ConnectionDB.executeSimpleQuery(query, binds);
}

I am now running a test in Test.ts where I am doing the following

Test.ts

it('Get Order method', function () {
    let req = {params: {testid: 12345}};
    let res = {
      status: '200'
    };

    //const dbConn = sinon.stub(xxxx, "xxxxxx").returns(true);

    TestController.getTest(req, res, Object);
});

I always get an error in the line which has ConnectionDB.executeSimpleQuery(query, binds); so I want to stub that out and return a sample json response and I am not sure how to do this with Sinon.


Solution

  • You can use sinon.stub() to make a stub for ConnectionDB.executeSimpleQuery method.

    E.g.

    controller.ts:

    import { ConnectionDB } from './db';
    
    export class Controller {
      static async getTest(req: any, res: any, next: object) {
        console.log('BEGIN -- TestController.getTest');
    
        let testid = req.params.testid;
        let query = `SELECT * FROM TEST WHERE TEST_ID = :1`;
        let binds: string[] = [testid];
    
        let result = await ConnectionDB.executeSimpleQuery(query, binds);
        console.log(result);
      }
    }
    

    db.ts:

    export class ConnectionDB {
      static async executeSimpleQuery(query, bindings) {
        return { message: 'real' };
      }
    }
    

    controller.test.ts:

    import { ConnectionDB } from './db';
    import { Controller } from './controller';
    import sinon from 'sinon';
    
    describe('61617621', () => {
      it('should pass', async () => {
        const logSpy = sinon.spy(console, 'log');
        const json = { message: 'fake' };
        const executeSimpleQueryStub = sinon.stub(ConnectionDB, 'executeSimpleQuery').resolves(json);
        const mReq = { params: { testid: 1 } };
        const mRes = {};
        const mNext = {};
        await Controller.getTest(mReq, mRes, mNext);
        sinon.assert.calledWithExactly(executeSimpleQueryStub, 'SELECT * FROM TEST WHERE TEST_ID = :1', [1]);
        sinon.assert.calledWithExactly(logSpy, { message: 'fake' });
      });
    });
    

    unit test results with coverage report:

      61617621
    BEGIN -- TestController.getTest
    { message: 'fake' }
        ✓ should pass
    
    
      1 passing (18ms)
    
    ---------------|---------|----------|---------|---------|-------------------
    File           | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
    ---------------|---------|----------|---------|---------|-------------------
    All files      |      90 |      100 |      50 |      90 |                   
     controller.ts |     100 |      100 |     100 |     100 |                   
     db.ts         |      50 |      100 |       0 |      50 | 3                 
    ---------------|---------|----------|---------|---------|-------------------