我对酶很陌生。我正在测试两个组件。

form.jsx

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

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


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

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
};


我已经为form编写了测试,并且通过了。

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;
    });


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

1-如何从onLogin测试Component.jsx中的form.jsx功能?

2-反之亦然,如果我必须从onSubmit触发form.jsxcomponent.jsx怎么办?

最佳答案

首先,您可以将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);
  });
});


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

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

09-20 22:48