嘲笑未模拟的方法

时间:2019-05-10 12:36:07

标签: javascript reactjs unit-testing ts-jest

我有一个React组件MyComponent,我想在其中测试用户旋转手机时应触发的行为。

在组件内部:

export class MyComponent extends React.PureComponent<props> {
  componentDidMount() {
    window.addEventListener('orientationchange', this.onRotation)
  }
  componentWillUnmount() {
    window.removeEventListener('orientationchange', this.onRotation)
  }

  onRotation = () => {
    // do things
  }

  render() {
    // ...
  }
}

我在媒介上找到了一篇文章,描述了如何为此here编写测试。但是,这对我不起作用。

describe('<MyComponent />', () => {
  it('does things on rotation', () => {
    const map : any = {}
    window.addEventListener = jest.fn((event, cb) => {
      map[event] = cb;
    })

    const wrapper : any = mount(<MyComponent />)
    map.orientationchange()

    expect(wrapper.onRotation).toHaveBeenCalled()
  })
})

在本文中,此方法有效,但是出现错误:

"Matcher error: received value must be a mock or spy function
Received has value: undefined"

使用间谍也不起作用:

it('does things on rotation', () => {
    const map : any = {}
    window.addEventListener = jest.fn((event, cb) => {
      map[event] = cb;
    })

    const wrapper : any = mount(<MyComponent />)
    const spy = jest.spyOn(wrapper.instance(), 'onRotation')

    map.orientationchange()
    expect(spy).toHaveBeenCalled()
})

它说:

"Expected mock function to have been called, but it was not called."

1 个答案:

答案 0 :(得分:2)

监视onRotation内部的函数。

import React from 'react';

class OrientationChange extends React.Component {
    componentDidMount() {
      window.addEventListener('orientationchange', this.onRotation)
    }
    componentWillUnmount() {
      window.removeEventListener('orientationchange', this.onRotation)
    }
    handleRotation = () => {
      console.log('inside handle rotation');
    }

    onRotation = (event) => {
      this.handleRotation()
    }

    render() {
        return (
          <div>Testing</div>
        )
    }
}

export default OrientationChange;

describe('<OrientationChange /> orientation change test', () => {
  it('does things on rotation', () => {
    const map = {}
    window.addEventListener = jest.fn((event, cb) => {
      map[event] = cb;
    })

    const wrapper = mount(<OrientationChange />)

    const spy = jest.spyOn(wrapper.instance(), 'handleRotation')
    map.orientationchange();

    expect(spy).toHaveBeenCalled()
  })
})