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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With