代码之家  ›  专栏  ›  技术社区  ›  GeraltDieSocke

为什么我的jest mock函数在使用Ezyme的“mount”函数时没有使用mock对象执行?

  •  0
  • GeraltDieSocke  · 技术社区  · 7 年前

    以下问题:

    我有这个部分:

    const TodoHeader = ({ handleChange, handleSubmit }) => {
      return (
        <form onSubmit={e => handleSubmit(e)}>
          <input
            type="text"
            onChange={e => handleChange(e.target.value)}
            placeholder="your todo.."
          />
        </form>
      );
    };
    

    通过以下测试:

    it("should call the passed in handleSubmit function with the event object", () => {
        const handleSubmit = jest.fn();
        const wrapper = mount(<TodoHeader handleSubmit={handleSubmit} />);
        const form = wrapper.find("form");
        console.log(form.debug());
        const mockEvent = { target: {} };
    
        form.simulate("submit", mockEvent);
    
        expect(handleSubmit).toHaveBeenCalledWith(mockEvent);
        // Why does this work with shallow but not with mount?
      });
    

    这将失败,因为函数已使用实际的onSubmit事件调用。尽管我在用我的自定义对象模拟它。

    当我对你做同样的事情时 shallow 而不是 mount 它会过去的

    这里有一个小的代码沙盒,可以对其进行测试。

    https://codesandbox.io/s/72yl24j59q

    1 回复  |  直到 7 年前
        1
  •  2
  •   Mohit Tilwani    7 年前

    您不必测试onSubmit是否与您传递的事件对象一起工作-这将测试React自身和浏览器,这与您无关。

    我已经更新了你提供的codesandbox链接,根据这个测试,所有测试用例现在都通过了。

    https://codesandbox.io/s/0op31650rp

    推荐文章