在这种情况下,如何以及用酶测试什么?

时间:2018-10-08 18:48:01

标签: reactjs unit-testing enzyme

在阅读了许多酶测试示例后,我迷路了,希望您能对我有所帮助。

提交表单时,将调用

handleSubmit()。它向远程服务器发出请求以保存数据。 当服务器返回响应后,将调用afterSubmit()回调,该回调将组件状态设置为成功:true,并呈现成功消息。

我要测试的是用户提交表单时显示成功消息。

我不知道是否应该模拟handleSubmit()函数以及如何或应该使用调度方法来做一些事情,以便它最终解决并调用afterSubmit()回调?

谢谢

import React, {Component} from 'react';
import {connect} from 'react-redux';
import {handleAddProduct} from '../actions/product';

class ProductForm extends Component {

  constructor(props) {
    super(props);

    this.state = {productName:'', success:false}

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.afterSubmit = this.afterSubmit.bind(this);
  }

  handleChange(event) {
    const value = event.target.value;
    this.setState(() => ({productName: value}));
  }

  handleSubmit(event) {
    event.preventDefault()

    const {productName} = this.state;
    this.props.dispatch(handleAddProduct(productName, this.afterSubmit));
  }

  afterSubmit() {
    this.setState(() => ({
        productName: '',
        success : true
    }));
  }

  render() {

    const {success} = this.state;

    return (
        <>
            {success && <p class="success">Success</p>}

            {!success &&
             <form onSubmit={this.handleSubmit} className="form">
                <input type="text" name="product-name" id="product-name" onChange={this.handleChange} value={this.state.productName} />
                <button type="submit">Submit</button>
             </form>
            }
        </>
    )

  }

}
export default connect()(ProductForm);

这是我开始的测试:

it('shows success message on submit', () => {
    const wrapper = shallow(<ProducForm store={mockStore} />);

    wrapper.find('input[name="product-name"]').simulate('change', { target: { value: 100 } })
    wrapper.find('button[type="submit"]').simulate('click')

    expect(wrapper.find('.success').exists()).toBe(true);
})

0 个答案:

没有答案