为了账号安全,请及时绑定邮箱和手机立即绑定

嘲笑未嘲笑的方法的调用

嘲笑未嘲笑的方法的调用

白衣染霜花 2021-05-13 14:13:00
我有一个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 functionReceived 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 回答

?
哔哔one

TA贡献1854条经验 获得超8个赞

监视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()

  })

})


查看完整回答
反对 回复 2021-05-27
  • 1 回答
  • 0 关注
  • 308 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信