【发布时间】:2017-07-19 22:43:35
【问题描述】:
以下内容:
const sinon = require('sinon')
const a = () => { return 1 }
sinon.stub(a)
抛出TypeError: Attempted to wrap undefined property undefined as function。
stub 在有对象的情况下有效,所以我尝试使用this。在 node.js REPL (v6.11) 中:
> const a = () => { return 1 }
undefined
> this.a
[Function: a]
但是,在我的 mocha 规范中,它失败了:
const a = () => { return 1 }
console.log(a)
// => [Function: a]
console.log(this.a)
// => undefined
我错过了什么?我怎样才能做到这一点?
顺便说一句:我知道我可以stub 一个对象的方法,就像这样:const stub = sinon.stub(object, 'a'),但这不是我在这里提出这个问题的目的。
【问题讨论】:
-
不是真正的重复。这与 setter/getter 无关。
-
你不能让它像这样工作。对于存根,Sinon 需要一个“根对象”,因为它需要替换您要在该根对象中存根的函数引用。 REPL 中的
this仅适用于 REPL 的实现方式。 -
@robertklep 显然你是对的。把这个写成答案,我会接受的。
-
@PawełGościcki 发布的答案基本上是一样的:)
标签: javascript testing sinon