如何使用Jest和Enzyme对包含history.push的react事件处理程序进行单元测试?

Dar*_*now 11 unit-testing html5-history reactjs jestjs enzyme

给出一个简单的组件:

export default class SearchForm extends Component {
  constructor(props) {
    super(props)
    this.state = { query: '' }
  }
  onSubmit = (event) => {
    event.preventDefault()
    history.push(`/results/${this.state.query}`, { query: this.state.query })
  }
  render() {
    return (
      <form onSubmit={this.onSubmit}>
        <input
          type="text"
          value={this.state.query}
          onChange={event => this.setState({ query: event.target.value })}
        />
        <button>Search</button>
      </form>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

而且测试:

describe('SearchForm Component', () => {
  it('should navigate to results/query when submitted', () => {
    const wrapper = shallow(<SearchForm />)
    ...?
  })
})
Run Code Online (Sandbox Code Playgroud)

如何验证表单提交是否将用户带到具有正确查询值的下一页?

我试过简单地模拟onSubmit处理程序并至少确认它已被调用,但这会导致安全性错误history.push.

const wrapper = shallow(<SearchForm />)
const mockedEvent = { target: {}, preventDefault: () => {} }
const spy = jest.spyOn(wrapper.instance(), 'onSubmit')
wrapper.find('form').simulate('submit', mockedEvent)
expect(spy).toHaveBeenCalled()
Run Code Online (Sandbox Code Playgroud)

rod*_*bbi 18

它实际上很简单,你可以将任何道具传递给组件,当它在测试中进行浅层渲染时,就像这样:
const wrapper = shallow(<SearchForm history={historyMock} />)

顺便说一句,在里面onSubmit,你应该打电话this.props.history.push(...).

现在,要创建一个模拟(文档中的更多信息),您可以在测试中这样写:
const historyMock = { push: jest.fn() };

请记住,您实际上只是在模拟对象的push方法history,如果在组件中使用更多方法并想要测试它们,则应该为每个测试创建一个模拟.

然后,您需要声明push模拟被正确调用.为此,您需要编写必要的断言:
expect(historyMock.push.mock.calls[0]).toEqual([ (url string), (state object) ]);
使用所需的断言(url string)(state object)断言.

  • 要添加答案,请记住,在浅渲染组件时可以传递所需的任何参数,而不仅仅是模拟。 (2认同)