首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在类构造函数中侦测绑定和调用的类方法?

如何在类构造函数中侦测绑定和调用的类方法?
EN

Stack Overflow用户
提问于 2018-02-02 01:03:45
回答 1查看 77关注 0票数 0

假设我有一个ES6 Target类:

代码语言:javascript
复制
class Target {

  constructor() {
    this.avoidDetection.bind(this) // not sure if necessary
    this.avoidDetection()
  }

  avoidDetection() {
    console.info('Nobody here but us chickens.')
  }
}

...and当avoidDetection方法在构造函数中被调用时,我想要监视该方法,以便:

代码语言:javascript
复制
const targetInstance = new Target() // Nobody here but us chickens.

// `spy` is spying on `avoidDetection`

console.log(spy.called === true) // true

我该怎么做呢?

EN

回答 1

Stack Overflow用户

发布于 2018-02-02 02:41:34

作为一种特定于React的解决方案,我将普通的ES6 Target类转换为React.Component的子类,以便可以利用酶的instance()方法。结果,我得到了以下工作:

代码语言:javascript
复制
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()
})
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48568105

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档