Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sinon stubbing helper method defined in same file

So I have a file, user-database, that looks something like this :

export function foo(id: number): Promise<boolean> {
  return new Promise<boolean>((resolve, reject) => {
    findSomething(id)
    .then((data) => {
      //do something with data
    })
  }
}

export function findSomething(id: number): Promise<Object> {
  return new Promise<Object> ((resolve, reject) => {
    let query = 'SELECT * FROM user';
    db.executeQuery(query);
    .then(data) => {
      if(data.length < 1) { reject(new Error('whoops')); }
      resolve(data);
    }, (err) => {
      reject(err);
    })
  })
}

So I am writing unit tests using Sinon for the exterior function, foo, and therefore I want to stub the function it calls, findSomething. I do this as follows:

import * as user_db from '../../src/user-database';

describe('POST /someEndpoint', () => {
  describe('when successful', () => {
    let stub;

    beforeEach(function() {
      stub = sinon.stub(user_db, 'findSomething');
    });

    afterEach(function() {
      stub.restore();
    }); 

    it('should respond with 200', function(done) {
      stub.returns(anObjectIPredefine);

      request(server)
        .post(basePath)
        .send(aPayloadIPredefine)
        .expect(200, done);
    });
  }
}

When I run the test, I don't see the object I am telling the stub to return with this stub.returns(anObjectIPredefine). I instead actually have the function findSomething execute as normal and grab data from the dB. Is there anything obvious I am doing wrong? My only guess is that stub = sinon.stub(user_db, 'findSomething') is not the proper syntax for stubbing a function defined in the same scope as the function being tested. I can't find what an alternative syntax would be though.

like image 377
TovrikTheThird Avatar asked Nov 09 '22 04:11

TovrikTheThird


1 Answers

So what I ended up doing was moving the functions I wished to stub to a different file. When this is done, stubbing works as intended. Probably not the best solution, but definitely a quick band-aid for anyone in a similar situation.

like image 184
TovrikTheThird Avatar answered Nov 14 '22 20:11

TovrikTheThird