React-i18next: Test container with multiple components translated

Created on 19 Dec 2016  路  5Comments  路  Source: i18next/react-i18next

I am trying to test a container that has multiple components inside. When I mount the container all the nested containers will be mounted but I have an error:

TypeError: Cannot read property 'getFixedT' of undefined

Some of my components are exporting with the translation decorator:

export const TextAreaCounterComponent = TextAreaCounter;

export default translate(['defaultNamespace'])(TextAreaCounterComponent);

How can I test this containers?

  const mockT = () => 'Hello';
  const middlewares = [];
  const mockStore = configureStore(middlewares);

  const initialState = {
    login: {
      loggedIn: true,
    },
    app: {
      isLoading: false,
      popupIsOpen: false,
      tabSelected: 0
    }
  };
  const store = mockStore(initialState);

  const wrapper = mount(
    <Provider store={store}>
      <Partner t={mockT} />
    </Provider>
  );

  it.only('should mount partner page container', () => {
    expect(wrapper.find('.wrap').length).toBe(1);
  });

Most helpful comment

  const mockI18n = {
    t(k) {
      return k;
    },
    on() {
    },
    getFixedT(k) {
      return (k) => k;
    },
    loadNamespaces(arg) {
      return (arg) => arg;
    }
  };
  const wrapper = mount(
    <I18nextProvider i18n={mockI18n}>
      <Provider store={store}>
        <Partner />
      </Provider>
    </I18nextProvider>
  );

This works

All 5 comments

do not test the component that is wrapped by higher order component - test the one without and pass a function t there ( function(k) { return k } );

For container -> sub components i use to pass the t function via prop to them. If you need it this way you need to wrap your test code inside a I18nProvider passing a mock i18next instance to it:

const mockI18n = {
  t(k) { return k },
  on() {}
}

as long as you do not use wait option this should work.

TypeError: this.i18n.getFixedT is not a function

  const mockI18n = {
    t(k) {return k;},
    on() {}
  };
  const wrapper = mount(
    <I18nextProvider i18n={mockI18n}>
      <Provider store={store}>
        <Partner t={mockT}/>
      </Provider>
    </I18nextProvider>
  );

Thanks for the quick support.

  const mockI18n = {
    t(k) {
      return k;
    },
    on() {
    },
    getFixedT(k) {
      return (k) => k;
    },
    loadNamespaces(arg) {
      return (arg) => arg;
    }
  };
  const wrapper = mount(
    <I18nextProvider i18n={mockI18n}>
      <Provider store={store}>
        <Partner />
      </Provider>
    </I18nextProvider>
  );

This works

TypeError: _i18next2.default.use is not a function

how do you import i18next? seems to be an issue related to import (using typescript?)

Was this page helpful?
0 / 5 - 0 ratings