【问题标题】:How can I spy on a class method bound and called in class constructor?如何监视在类构造函数中绑定和调用的类方法?
【发布时间】:2018-07-12 02:15:43
【问题描述】:
假设我有一个 ES6 Target 类:
class Target {
constructor() {
this.avoidDetection.bind(this) // not sure if necessary
this.avoidDetection()
}
avoidDetection() {
console.info('Nobody here but us chickens.')
}
}
...当avoidDetection 方法在构造函数内部被调用时,我想监视它:
const targetInstance = new Target() // Nobody here but us chickens.
// `spy` is spying on `avoidDetection`
console.log(spy.called === true) // true
我该怎么做?
【问题讨论】:
标签:
unit-testing
ecmascript-6
jestjs
sinon
es6-class
【解决方案1】:
作为一种特定于 React 的解决方案,我将普通的 ES6 Target 类转换为 React.Component 的子类,以便我可以利用 Enzyme 的 instance() 方法。结果,我得到了以下工作:
beforeEach(() => {
targetAvoidDetectionSpy = spyOn(Target.prototype, 'avoidDetection')
targetWrapper = mount(<Target />)
targetInstance = targetWrapper.instance()
})
it('is an instance of Target', () => {
expect(targetInstance).toBeInstanceOf(Target)
})
it('avoids detection (not really)', () => {
expect(targetAvoidDetectionSpy).toHaveBeenCalled()
})