尝试使用Sinon存根链接的knex查询。查询如下所示
const result = await TableModel
.query()
.whereIn('id', idList)
.whereIn('value', valueList);
通常我使用一个我创建的辅助函数,它返回一个模型实例,每个方法都存根以返回this
,就像这样
for (const method of ['query', 'whereIn']) {
TableModel[method] = sandbox.stub().returnsThis();
}
然后在测试中对实例进行存根以解决必要的测试用例
TableModel.whereIn = sandbox.stub().resolves({ object: 'stuff' });
但是,当链接相同的方法时,这不起作用我从mocha / chai / sinon读取错误
TypeError: TableModel.query(...).whereIn(...).whereIn is not a function
寻求有关如何在测试中存根和解析方法的帮助。
我一直试图存根类似的情况:
await model.query().findById();
我能够通过以下方式存根:
const stubbedData = { ... }; // Whatever you want to get
sandbox.stub(Model, 'query').returns({
findById: sandbox.stub().returns(stubbedData),
});
在你的情况下,它将非常相似,如果你需要区分两个whereIn
然后你可以使用withArgs
或第一个whereIn
可以返回另一个“嵌套”存根。
这是一篇关于存根复杂对象的好文章: