问题描述
所以我有一个文件user-database
,看起来像这样:
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);
})
})
}
因此,我正在使用Sinon编写外部函数foo
的单元测试,因此我想对它调用的函数findSomething
进行存根.我这样做如下:
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);
});
}
}
运行测试时,我看不到告诉存根随该stub.returns(anObjectIPredefine)
返回的对象.实际上,我实际上让函数findSomething
正常执行,并从dB中获取数据.有什么明显的地方我做错了吗?我唯一的猜测是stub = sinon.stub(user_db, 'findSomething')
不是对与测试功能在相同范围内定义的功能进行存根的正确语法.我找不到什么替代语法.
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.
这篇关于在同一文件中定义的Sinon存根辅助方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!