score:17

Accepted answer

One can test this without relying on sinon. By expecting that the onLoad and onFire event listeners are invoked,the tests check if the img fires the load and error events.

Instead,simulate img's events using enzyme and check that the appropriate state transition occurs:

it('has a state of LOADED if a good src prop is supplied', () => {
  const wrapper = shallow(<Image 
    src="anyString.jpg"
    width={300}
    height={300}
  />);

  const img = wrapper.find('img');
  img.simulate('load');
  const status = wrapper.state().status;
  expect(status).to.equal('LOADED');
});

This also eliminates the need to mount the component. The updated tests can be found here.

score:0

The main issue I see with this approach is that the state is an internal thing, and not something that should be known outside the component. Now you are leaking state information ("status" in this case) out into the tests.

Doing this means you are not doing "black-box testing", which is the most valuable type of tests. You are leaking the implementation details of the component. In other words "Encapsulation" should be highly considered.

There are perhaps better ways to test this. You could for instance export a presentational component as well, which takes the parts of the state you need to test as props. Or look for an element that would be rendered when status is "LOADED" with enzyme find method.


Related Query

More Query from same tag