反应路由器V4对反应组件的浅层测试

时间:2018-02-08 17:37:59

标签: reactjs jest

我试图用Jest + Enzyme对我的React登录组件进行浅层测试,但是我遇到了React Router V4的问题。当测试运行时,我从Jest声称:

收到错误
cannot read property push of undefined.

这是我的测试,下面是我正在测试的组件内部的方法。

describe('Login Component', () => {
  let wrapper
  const mockSignInFunc = jest.fn()

  beforeEach(() => {
    wrapper = shallow(<Login signIn={mockSignInFunc} />)
  })

  it('renders itself', () => {
    expect(wrapper.find('.login').length).toEqual(1)
  })

  it('should call the signIn function on submittal', () => {
    wrapper.find('form').simulate('submit', { preventDefault() {}})
    expect(mockSignInFunc.mock.calls[0][0]).toBe(1)
  })

}) // end describe block

正在测试的方法:

handleSubmit = e => {
  e.preventDefault()
  this.props.signIn()
  this.props.history.push('/') // fails here
}

如果我删除了this.props.history.push(&#39; /&#39;)代码行,则测试通过,所以我知道这是一个React Router问题。我尝试阅读其他一些文档,其中将组件包装在MemoryRouter中应该可以工作,但是通常情况下,React Router文档还有很多不足之处。

我实际上在我的应用程序中使用HashRouter,并且不确定使用MemoryRouter是否只是一个让它工作的黑客。打败我。

有谁知道如何让这个测试通过?

1 个答案:

答案 0 :(得分:2)

您正在测试行为。您希望使用某个值调用历史记录,因此您需要模拟它并将其传递给组件。

const history = {push:jest.fn()}

并检查是否被调用