首页 > 解决方案 > 未模拟的方法的开玩笑测试调用

问题描述

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

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

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

标签: javascriptreactjsunit-testingts-jest

解决方案


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

推荐阅读