猿问

嘲笑未嘲笑的方法的调用

我有一个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() {

    // ...

  }

}

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


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."


白衣染霜花
浏览 309回答 1
1回答

哔哔one

监视onRotation内部的函数。import React from 'react';class OrientationChange extends React.Component {&nbsp; &nbsp; componentDidMount() {&nbsp; &nbsp; &nbsp; window.addEventListener('orientationchange', this.onRotation)&nbsp; &nbsp; }&nbsp; &nbsp; componentWillUnmount() {&nbsp; &nbsp; &nbsp; window.removeEventListener('orientationchange', this.onRotation)&nbsp; &nbsp; }&nbsp; &nbsp; handleRotation = () => {&nbsp; &nbsp; &nbsp; console.log('inside handle rotation');&nbsp; &nbsp; }&nbsp; &nbsp; onRotation = (event) => {&nbsp; &nbsp; &nbsp; this.handleRotation()&nbsp; &nbsp; }&nbsp; &nbsp; render() {&nbsp; &nbsp; &nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div>Testing</div>&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; }}export default OrientationChange;describe('<OrientationChange /> orientation change test', () => {&nbsp; it('does things on rotation', () => {&nbsp; &nbsp; const map = {}&nbsp; &nbsp; window.addEventListener = jest.fn((event, cb) => {&nbsp; &nbsp; &nbsp; map[event] = cb;&nbsp; &nbsp; })&nbsp; &nbsp; const wrapper = mount(<OrientationChange />)&nbsp; &nbsp; const spy = jest.spyOn(wrapper.instance(), 'handleRotation')&nbsp; &nbsp; map.orientationchange();&nbsp; &nbsp; expect(spy).toHaveBeenCalled()&nbsp; })})
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答