node.js - Objection.js Stubbing Chained "whereIn"方法与 Sinon

标签 node.js sinon knex.js objection.js

尝试使用 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 的好文章:

https://codeutopia.net/blog/2016/05/23/sinon-js-quick-tip-how-to-stubmock-complex-objects-such-as-dom-objects/

关于node.js - Objection.js Stubbing Chained "whereIn"方法与 Sinon,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50957424/

相关文章:

javascript - Sinon clock.tick 不会提前 setTimeout 的时间

node.js - Sinon:强制回调调用

google-cloud-platform - 如何使用 sinon 、 mocha chai 模拟以下代码的响应

javascript - 我们总是可以使用 knex 和 postgres 将日期列作为字符串 (varchar) 获取吗?

Mysql 的 Express 查询返回 null

node.js - Nodemailer:连接超时错误

events - 为什么 node.js 将传入数据分成 block ?

node.js - Ember : handlebars does not satisfy its siblings' peerDependencies

node.js - 如何使用 Knex 获取与我正在查询的表相关的行

mysql - KnexJS 具有多个表和别名