酶:如何测试作为prop传递的onSubmit函数? [英] Enzyme: How to test onSubmit function passed as prop?

查看:131
本文介绍了酶:如何测试作为prop传递的onSubmit函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对酶很陌生。我有两个要测试的组件。

I am fairly new with enzyme. I have two components under test.

form.jsx

const LoginForm = ({ style, handleSubmit }) => {
  return (
    <form onSubmit={handleSubmit}>
        <Button type='submit'>
          Login
        </Button>
    </form>
  );
};

LoginForm.propTypes = {
  handleSubmit: PropTypes.func.isRequired
};

我正在另一个组件中使用此组件,如下所示:

I am using this component in another component as follows:

Component.jsx

export default class Login extends Component {
  constructor(props) {
    super(props);
    this.onLogin = this.onLogin.bind(this);
  }

  onLogin(event) {
    event.preventDefault();
    this.props.loginUser();
  }
  render() {
    return (
      <LoginForm style={loginFormStyles} handleSubmit={this.onLogin} />      
    );
  }
}

Login.propTypes = {
  auth: PropTypes.object.isRequired, //mapStateToProps
  loginUser: PropTypes.func.isRequired //mapDispatchToProps
};

我已经为表格编写了测试,

I have written tests for form and they are passing.

form-test.js

 it('should have a onSubmit handler', () => {
      const props = {
        handleSubmit: () => {}
      };
      const wrapper = shallow(<LoginForm {...props} />);
      expect(_.isFunction(wrapper.props().onSubmit)).to.be.true;
    });

    it('should should call handlesubmit on form submission', () => {
      const handleSubmit = sinon.spy();
      const wrapper = shallow(<LoginForm handleSubmit={handleSubmit} />);
      wrapper.simulate('submit');
      expect(handleSubmit).to.have.been.called;
    });

这些测试通过了。令人困惑的部分是:

These tests are passing. The confusing part is:

1-如何测试组件中的 onLogin 函数。 jsx 来自 form.jsx

1- How do I test onLogin function in Component.jsx from form.jsx?

2-反之亦然,如果我必须触发 form.jsx onSubmit / code>来自 component.jsx 我该怎么做?

2- Vice versa, if I have to trigger onSubmit of form.jsx from component.jsx how would I do that?

推荐答案

首先,您可以将 Component.jsx 重命名为其他名称。

First of all, you can rename the Component.jsx to something else.

对于测试,您可以执行以下操作,

And for the test you can do something as below,

import Component from '../src/login';
import { stub } from 'sinon';


describe('login', () => {
  it('should call onsubmit', () => {
    const onSubmit = stub()
      .withArgs('username', 'password');
    const loginComponent = mount(<LoginForm  handleSubmit={onSubmit} /> );
    loginComponent.simulate('submit');
    expect(onSubmit.calledOnce).to.equal(true);
  });
});

我尚未对此进行测试,但它与您正在查看的内容很接近。

I have not tested this but it is close to what you are looking at.

更新:
我已经测试过并且可以正常工作。

Update: I tested this and it is working.

这篇关于酶:如何测试作为prop传递的onSubmit函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆