Search code examples
unit-testingreactjssinonenzymesinon-chai

Enzyme: Test fails on BrowserHistory function


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.


Solution

  • 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')