unit-testing - Enzyme:如何测试作为 prop 传递的 onSubmit 函数?

标签 unit-testing reactjs redux sinon enzyme

我对 enzyme 还很陌生。我有两个正在测试的组件。

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- 如何从 form.jsx 测试 Component.jsx 中的 onLogin 函数?

2- 反之亦然,如果我必须从 component.jsx 触发 form.jsxonSubmit 我该怎么做?

最佳答案

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

我尚未对此进行测试,但它与您所看到的很接近。

更新: 我测试了这个并且它有效。

关于unit-testing - Enzyme:如何测试作为 prop 传递的 onSubmit 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38940318/

相关文章:

ios - 生成 iOS/Swift 代码覆盖率测试报告

c# - 如果 "Presenter"在 "View"上设置属性是否违反了 MVP 模式?

redux - 更改数组项的最佳方法是什么?

javascript - 在 Jest 中模拟类模块

python - 在 python 中组合断言

css - 使用 react-bootstrap 进行网格布局时遇到问题

javascript - react native : pass string as function

javascript - 在 Redux 中设置应用挂载的存储状态

node.js - Sails-React : Access props from Parent Component

reactjs - axios 将数据作为表单数据发布,而不是作为有效负载中的 JSON