How to test components wrapped in "withNamespaces" HOC that have "innerRef"?

Viewed 318

I added i18n to my react app using react-i18next. I have a component A that uses a ref to a child component B like this:

A.jsx:

class A extends Component {
  constructor() {
    super(this.props);
    this.refToB = null;
  }

  render() {
    return (
      <B
        setBref={(ref) => this.refToB = ref}
        prop1="prop1"
        prop2="prop2"
      />
    );
  }
}

B.jsx:

class B extends Component {
  render() {
    return (
      <div>Some content...</div>
    );
  }
}

export default withNamespaces(null, {
  innerRef: (ref) => {
    ref.props.setBref(ref)
  }
})(B);

Now I want to test component A, so I created a mock to withNamespaces like this:

export const withNamespaces = (ns, options) => (Component) => {
    if (options && options.innerRef) {
        // ***What can I do here?***
    }
    Component.defaultProps = { ...Component.defaultProps, t: key => key };
    return Component;
}

How can I implement a test for this? how can I actually pass the innerRef function the actual reference that was created in the test?

1 Answers

You can use jest.mock to mock the i18n module and provide your own mock implementation:

jest.mock('<import path to i18n>', () => ({
    withNamespaces: () => Component => {
        Component.defaultProps = { ...Component.defaultProps, t: key => key };
        return Component;
    },
}));

Note that the import path should be either the module name if importing directly from node_modules, or the file path relative to the test file if importing from within the project.

Related