考虑以下 react 组件。
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
从 redux
调用我们自定义的 loginFormSubmit
。如何检查在 handleSubmit
中调用了 loginFormSubmit
。这是我到目前为止的测试
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();
});
});
});
最佳答案
从中导入函数的模块应该在测试的顶部被模拟:
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(...);
关于reactjs - 开 Jest 如何检查 spy 函数中被调用的 spy 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52981537/