enzymejs / enzyme

JavaScript Testing utilities for React
https://enzymejs.github.io/enzyme/
MIT License
19.96k stars 2.01k forks source link

spy on component method failed #365

Closed tpai closed 8 years ago

tpai commented 8 years ago

I'm now using class properties feature on component method, but the spy seems not work.

The component like this:

// Sample.js
export default class Sample extends Component {
  sampleMethod = () => {
    console.log("sample");
  }
  render() {
    return (<button onClick={this.sampleMethod}>Sample</button>);
  }
}

Test code here:

// Sample.test.js
import { mount } from "enzyme";
import expect from "expect";
import Sample from "./Sample.js";

const wrapper = mount(<Sample />);
const spy = expect.spyOn(wrapper.instance(), "sampleMethod");
expect(spy).toNotHaveBeenCalled();
wrapper.find("#sample").simulate("click");
expect(spy).toHaveBeenCalled();

The result is spy was not called, is that class properties issue or just I wrote wrongly?

ljharb commented 4 years ago

@Geczy yes, it absolutely is, and has always done so with its use of arrow functions in class fields.

The babel transform exists because the spec allows for functions in fields (because it'd be weird for it not to permit it) and the transform has to follow the spec. That's utterly irrelevant to whether you should use certain patterns.