酶按类别名称查找并模拟单击

时间:2019-05-01 06:48:35

标签: reactjs enzyme

在酶中,模拟单击className找到的项目似乎无效。问题在于,mockFn没有嘲笑toggleSort。但是在其他情况下,以这种方式模拟功能的效果很好。为什么酶处理模拟类函数的方式不一致?以下所有用于测试事件处理程序toggleSort的情况都不起作用。

import React from "react";

export default class Hello extends React.Component {
  toggleSort = e => {
    console.log(e, "dd");
  };
  render() {
    return (
      <button type="button" className="button" onClick={this.toggleSort} />
    );
  }
}

测试:

import React from "react";

import Enzyme, { shallow } from "enzyme";
import Adapter from "enzyme-adapter-react-16";

import Hello from "./Hello";

Enzyme.configure({ adapter: new Adapter() });

describe("Hello", () => {
  it("should do the right thing", async () => {
    const mockFn = jest.fn();
    const component = shallow(<Hello />);

    component.instance().toggleSort = mockFn;

    await component
      .find(".button")
      .at(0)
      .simulate("click");

    expect(mockFn).toBeCalled();
  });

  it("should work with spy", () => {
     const component = shallow(<Hello />);
     const spy = jest.spyOn(component.instance(), "toggleSort");
     component.update();
     component
       .find(".button")
       .at(0)
       .simulate("click");
     expect(spy).toHaveBeenCalled();
   });

   it("should work with prototype", () => {
    const mockFn = jest.fn()
    Hello.prototype.toggleSort = mockFn
    const component = shallow(<Hello />);
    component
      .find(".button")
      .at(0)
      .simulate("click");
    expect(mockFn).toHaveBeenCalled();
  });
});

下面是codeandbox上的测试文件 https://codesandbox.io/s/n0jv07kqll

1 个答案:

答案 0 :(得分:0)

toggleSort是一个实例属性,由于类原型中不存在该实例,因此您必须使用该实例进行模拟。

onClick直接绑定到this.toggleSort,所以您要么不得不强制重新渲染,然后将其重新绑定到您的间谍:

it("should work with spy", () => {
  const component = shallow(<Hello />);
  const spy = jest.spyOn(component.instance(), "toggleSort");
  component.setState({});  // <= force re-render (sometimes component.update() isn't enough)
  component
    .find(".button")
    .at(0)
    .simulate("click");
  expect(spy).toHaveBeenCalled();  // Success!
});

...或使用箭头函数调用它,以便调用this.toggleSort的当前值:

<button type="button" className="button" onClick={() => this.toggleSort()} />

...然后可以像这样进行测试:

it("should work with spy", () => {
  const component = shallow(<Hello />);
  const spy = jest.spyOn(component.instance(), "toggleSort");
  component
    .find(".button")
    .at(0)
    .simulate("click");
  expect(spy).toHaveBeenCalled();  // Success!
});