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