我怎样才能窥探在类构造函数中绑定和调用的类方法?

时间:2018-02-01 17:03:45

标签: unit-testing ecmascript-6 jestjs sinon es6-class

说我有一个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

我该怎么做?

1 个答案:

答案 0 :(得分:0)

As one React-specific solution, I converted my plain ES6 Target class into a child of React.Component so that I could take advantage of Enzyme's instance() method. As a result, I got the following to work:

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()
})