Search code examples
reactjstestingi18nextreact-i18next

Unit Test Coverage with react-i18next


I have a fairly simple React component with Internationalization features implement using i18next. The version of i18next that I'm using is 11.9.0, and the version of react-i18next I'm using is 8.1.0. The component (and specs) looks something like this:

TestComponent.component.js

import React, { Component } from "react";
import { I18n } from "react-i18next";

export class TestComponent extends Component {
  render() {
    return (
      <I18n ns="translations">
        { t => (
          <p>
            {t('test')}
          </p>
        )}
      </I18n>
    );
  }
}

export default TestComponent;

TestComponent.component.spec.js

import React from "react";
import { I18n } from "react-i18next";
import { shallow } from "enzyme";

import TestComponent from './TestComponent.component';

describe('TestComponent', () => {
  describe('Snapshot Test', () => {
    it('it matches snapshot', () => {
      const wrapper = shallow(<TestComponent />);
      wrapper.instance().render();
      expect(wrapper.instance()).toMatchSnapshot();
    });
  });
});

I'm trying to test this component using Jest Snapshots, but when I check the code coverage for this component, it shows that the t function is not being reached by the coverage checker.

I imagine that this can be resolved by mocking I18n in some way, but none of the examples I've found online which do this have resolved my issue.

Can anybody provide some insight into why the coverage checker isn't reaching the t function here? What needs to be done in order to bump up my coverage for a component like this?


Solution

  • Disclaimer: I'm not sure if HOC is valid term for component that renders another component through children callback. Let me know if I have to correct wording.

    3 different approaches available:

    1. using dive() you are able to drill through HOC still using shallow() render.

    2. exporting both HOCed and raw version of component - with writting unit tests for raw version.

    3. using mount() instead of shallow() - as for me it's overkill and may lead to unexpected circumstances.