Search code examples
javascriptreactjsfirebasejestjsreact-test-renderer

Mocking props from HOC in react for snapshot tests


I am trying to appropriately mock props for a simple sign out button component. The only prop in this component is the firebase prop which is coming from a Higher Order Component (HOC) called withFirebase.

import React from 'react';
import { withFirebase } from '../Firebase';

const SignOutButton = ({ firebase }) => (
  <button type="button" onClick={firebase.doSignOut}>
    Sign Out
  </button>
);

export default withFirebase(SignOutButton);
export { SignOutButton as SignOutButtonTest };

My thought was that I could export the functional component without the HOC and mock the firebase prop directly and pass that to the component for the snapshot test.

import React from 'react';
import renderer from 'react-test-renderer';
import SignOutButtonTest from '../SignOutButton';

describe('SignOutButton Tests', () => {
    it('renders with some data', () => {
        const props = {
            firebase: {
                doSignOut: () => {},
            }
        };
        const tree = renderer.create(
            <SignOutButtonTest {...props} />
        ).toJSON();
        expect(tree).toMatchSnapshot();
    });
});

However, when I run this test I get the following TypeError. Any thoughts on how to properly mock this firebase prop for a snapshot test?

  ● SignOutButton Tests › renders with some data

    TypeError: Cannot read property 'doSignOut' of null

      3 | 
      4 | const SignOutButton = ({ firebase }) => (
    > 5 |   <button type="button" onClick={firebase.doSignOut}>
        |                                           ^
      6 |     Sign Out
      7 |   </button>
      8 | );

Solution

  • Use named export instead of default export. Here:

    import SignOutButtonTest from '../SignOutButton';
    

    you are still importing HOC'ed version.

    It should be:

    import { SignOutButtonTest } from '../SignOutButton';