шутить тестовый вызов метода, который не поругаем - PullRequest
1 голос
/ 10 мая 2019

У меня есть React Component 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."

1 Ответ

2 голосов
/ 10 мая 2019

Шпионская функция внутри 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()
  })
})
...