1

I am fairly new to unit tests. I am using react+redux and I have created a NotFound page/component and I am writings its unit test. There's an onClick event that I need to test which is failing.

404.jsx

const GenericNotFound = () => {
  const goBack = () => {
    browserHistory.goBack();
  };
  return (
    <section >
      <h1>Sorry. The requested URL is not found</h1>
      <a onClick={goBack}>Go back</a>
    </section>
  );
};

Test.js

 const wrapper = shallow(<GenericNotFound />);
  const browserHistory = {
    goBack: sinon.spy()
  };
  const onClick = wrapper.find('a').props().onClick;
  onClick();
  expect(browserHistory.goBack).to.have.been.called;

Even with this, it throws me an error Cannot read property 'goBack' of undefined

Thank you in advance.

Umair Sarfraz
  • 5,284
  • 4
  • 22
  • 38

2 Answers2

2

By following @anoop answer:

 it('should render an anchor tag', () => {
      sinon.spy(browserHistory, 'goBack');
      const wrapper = mount(<GenericNotFound />;
      const onClick = wrapper.find('a').props().onClick;
      onClick();
      expect(browserHistory.goBack).to.have.been.called;
      browserHistory.goBack.restore();
    });
Umair Sarfraz
  • 5,284
  • 4
  • 22
  • 38
0

As updated on the comments,

some changes

  1. Use mount instead of shallow

const mount = mount(<GenericNotFound />);

  1. Use spy as below,

sinon.spy(browserHistory.prototype, 'goBack')

anoop
  • 3,229
  • 23
  • 35