Sinon stubbing helper method defined in same file

僤鯓⒐⒋嵵緔 提交于 2019-12-23 09:52:37

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/41171402/sinon-stubbing-helper-method-defined-in-same-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!