1

I'm trying to mock my sequlize db call Below is the example

it('mock db call', async() => {
    sinon.stub(DBNAME, 'scope').resolves()
    sinon.stub(DBNAME, 'findAll').resolves(dbDetails)
    const res = await func1();
    sinon.assert.match(res, dbDetails);
})

function func1 is as below

const func1 = async () => {
    const getData = await DBNAME.scope(
      'includeEverything',
    ).findAll();
    return getData
}

Does anyone knows how to stub scope and findAll at same time.

i'm getting error as below

TypeError: models_1.DBNAME.scope(...).findAll is not a function

I'm trying to test func1 and stub 'scope' and 'findAll'.

Lin Du
  • 88,126
  • 95
  • 281
  • 483
ktn987
  • 11
  • 2

1 Answers1

0

You should use sinon.stub().returnThis() to stub the method chain calls.

index.ts:

import { DBNAME } from './db';

export const func1 = async () => {
  const getData = await DBNAME.scope('includeEverything').findAll();
  return getData;
};

db.ts:

export const DBNAME = {
  scope(arg) {
    return this;
  },
  findAll() {
    return this;
  }
};

index.test.ts:

import sinon from 'sinon';
import { func1 } from '.';
import { DBNAME } from './db';

describe('75529424', () => {
  it('mock db call', async () => {
    const dbDetails = {};
    sinon.stub(DBNAME, 'scope').returnsThis();
    sinon.stub(DBNAME, 'findAll').resolves(dbDetails);
    const res = await func1();
    sinon.assert.match(res, dbDetails);
  });
});

Test result:

  75529424
    ✓ mock db call


  1 passing (7ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |      75 |      100 |      50 |   71.43 |                   
 db.ts    |   33.33 |      100 |       0 |   33.33 | 3-6               
 index.ts |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------
Lin Du
  • 88,126
  • 95
  • 281
  • 483