reactjs - 开 Jest 如何检查 spy 函数中被调用的 spy 函数?

标签 reactjs redux jestjs enzyme

考虑以下 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 在提交表单时被调用。 handleSubmitredux 调用我们自定义的 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/

相关文章:

reactjs - 使用 Jest 和 Redux 的异步组件快照

javascript - 如何用 Jest 覆盖(或模拟)类方法以测试函数?

javascript - 如果在 React Native 中未选中所有复选框,如何禁用按钮

javascript - 理解react-redux中connect()函数的语法

reactjs - Material-ui - TextField - 无法更改辅助文本错误颜色

javascript - 无法在我的 create-react-app 中从 'redux-saga' 导入 createSagaMiddleware

android - 从 ReactNative-DatePickerAndroid 获取选定日期

javascript - 本地package.json存在,但缺少node_modules

javascript - 在 React Jest/Enzyme 中测试子组件的条件渲染

reactjs - 在测试 react 组件和运行测试覆盖率时,这些绿色数字代表什么?