酶:如何测试onSubmit函数作为prop传递?

Uma*_*raz 4 unit-testing sinon reactjs redux enzyme

我对酶很新.我有两个正在测试的组件.

form.jsx

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

LoginForm.propTypes = {
  handleSubmit: PropTypes.func.isRequired
};
Run Code Online (Sandbox Code Playgroud)

我在另一个组件中使用此组件如下:

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
};
Run Code Online (Sandbox Code Playgroud)

我已经写了测试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;
    });
Run Code Online (Sandbox Code Playgroud)

这些测试正在通过.令人困惑的部分是:

1 -如何测试onLogin在功能上Component.jsxform.jsx

2 -反之亦然,如果我有触发onSubmitform.jsxcomponent.jsx我会怎么做呢?

ano*_*oop 7

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

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

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);
  });
});
Run Code Online (Sandbox Code Playgroud)

我没有对此进行过测试,但它与您正在观察的内容非常接近.

更新:我测试了它,它正在工作.