【问题标题】:Unexpected Sinon.js behaviour意外的 Sinon.js 行为
【发布时间】:2017-05-11 20:40:13
【问题描述】:

我正在尝试使用 MochaSinon.js 存根 Stripe 模块进行单元测试。

我需要这样的条纹:

const stripe = require('stripe');
const stubbedStripeClient = stripe.Stripe('test');

在我的测试的根源(在我的顶级describe())我有这个:

before('stub root', () => {
  sinon.stub(stripe, 'Stripe').returns(stubbedStripeClient);
});

然后,在我实际上会调用 Stripe 方法的 describe() 块中,我有这个 before() 钩子:

let stub;
before('stub', () => {
  console.log(typeof stubbedStripeClient.customers.create);
  stub = sinon.stub(stubbedStripeClient.customers, 'create', ({id: 'a-stripe-customer-id'}));
});

这是我不明白会发生什么的地方。钩子中的第一行 (console.log) 输出:

功能

第二行抛出这个异常:

TypeError: Attempted to wrap undefined property create as function

这怎么可能?怎么可能在一行上是一个函数,而在下一行却是未定义的?

我查看了 Sinon.js 源代码,并执行了此检查 here。如果我再查看他们的isFunction 函数,它会执行与我在console.log 中相同的检查。我很困惑。

【问题讨论】:

  • 一条线索,存根调用的第三个参数不是函数而是对象。 Looks like 它必须是一个函数。
  • 哇哦。我实际上希望这不是解决方案,但它现在确实有效......我真的需要对此进行外部查看,我只是忘记了 () => 来声明一个函数,所以正如你所说,我是通过一个普通的对象作为第三个参数。但是错误消息不是很清楚:/非常感谢@Will

标签: javascript node.js sinon


【解决方案1】:

这是一个令人遗憾且具有误导性的错误消息。

存根调用的第三个参数不是函数而是对象。从the docs 开始,它需要是一个函数。

要解决,请更改:

({id: 'a-stripe-customer-id'})

类似于:

() => { return {id: 'a-stripe-customer-id'}; }

...如果您想返回该对象,或者您的意思是将对象作为参数:

({id: 'a-stripe-customer-id'}) => {}

【讨论】:

  • 是的,这就是问题所在。第三个参数应该是一个返回{id: 'a-stripe-customer-id'} 对象的函数。我只是忘记了它前面的() =>。但是在我的情况下,.returns() 会比第三个参数更合适,并且不会导致这个错误
猜你喜欢
  • 1970-01-01
  • 2020-10-04
  • 2016-07-16
  • 2016-05-10
  • 2020-07-23
  • 2021-08-23
  • 2021-11-16
  • 2017-10-20
  • 2016-06-29
相关资源
最近更新 更多