考虑以下反应成分。
import React, { Component } from "react";
import { reduxForm, Field } from "redux-form";
import { connect } from "react-redux";
import formFields from "components/Login/formFields";
import LoginField from "components/Login/LoginField/LoginField";
import _ from "lodash";
import { loginFormSubmit } from "store/actions/profile/profile";
import { SubmissionError } from "redux-form";
export class Login extends Component {
renderFields() {
return _.map(formFields, ({ label, name }) => {
return (
<Field
component={LoginField}
type="text"
key={label}
label={label}
name={name}
/>
);
});
}
render() {
const { handleSubmit, history } = this.props;
return (
<div>
<form
onSubmit={handleSubmit(values =>
loginFormSubmit(values, history, SubmissionError)
)}
>
{this.renderFields()}
<button type="submit">Send the Survey</button>
</form>
</div>
);
}
}
export default connect(
null,
{ loginFormSubmit }
)(
reduxForm({
form: "loginform"
})(Login)
);
提交表单后,您会看到handleSubmit
被调用。 handleSubmit
从loginFormSubmit
调用我们的自定义redux
。如何检查loginFormSubmit
中是否调用了handleSubmit
。到目前为止,这是我的测试
import { Login } from "components/Login/Login";
import { shallow } from "enzyme";
import React from "react";
describe("The Login component description", () => {
describe("The Login component", () => {
const props = {
handleSubmit: jest.fn()
};
it("should call handleSubmit on form submission", () => {
const wrapper = shallow(<Login {...props} />);
wrapper.find("button").simulate("click");
expect(props.handleSubmit).toHaveBeenCalled();
});
});
});
答案 0 :(得分:1)
导入功能的模块应在测试顶部进行模拟:
import { loginFormSubmit } from "store/actions/profile/profile";
jest.mock('store/actions/profile/profile', () => ({ loginFormSubmit: jest.fn() }));
然后可以断言:
expect(props.handleSubmit).toHaveBeenCalledWith(expect.any(Function));
expect(loginFormSubmit).not.toHaveBeenCalled(...);
props.handleSubmit.mock.calls[0][0]()
expect(loginFormSubmit).toHaveBeenCalledWith(...);