Perp
Perp

Reputation: 403

how to mock i18next module in jest

I'm setting up test environment for existing Vue project, and I decided on jest with vue-test-utils.

Everything is installed and in place, however when I import component I wish to test in .test.js file, and add component to test utils like so:

let wrapper = shallow(Home)

test suite crashes with error: TypeError: Cannot read property 'i18next' of undefined.

I decided to mock i18next module but I have problems with mocking. My mock looked like this:

jest.mock('i18next', () => ({
  init: () => {},
  use: () => {},
  t: k => k
}));

but I always get error:

TypeError: Cannot read property 'init' of undefined

      35 |
      36 | i18next
    > 37 |      .use(Locize)
      38 |      .init(i18nextOptions);
      39 |
      40 | export default new VueI18Next(i18next);

Can somehow explain the proper way to mock i18next module so my wrapper object could initialize ? Also if I'm doing something else wrong, please point me in the right direction. Below is the complete test case:

import { shallow, mount, createLocalVue } from '@vue/test-utils';
import Home from '../../src/app/pages/home/index/index.vue';

jest.mock('i18next', () => ({
  init: () => {},
  use: () => {},
  t: k => k
}));

describe('Home Component', () => {

  let wrapper;

  beforeEach(() => {
    wrapper = shallow(Home);
  });

  it('something', () => {
    console.log('bleh');
    expect(wrapper.contains('div')).toBe(true);
  });

});

Thanks.

Upvotes: 4

Views: 7519

Answers (1)

daniloisr
daniloisr

Reputation: 1367

The error Cannot read property 'init' of undefined happens on the result of i18next.use(Locize) and not on the i18next object. Try updating your mock to:

jest.mock('i18next', () => ({
  use: () => {
    init: () => {
      t: k => k,
      on: () => {}
    }
  }
}));

I used this file as reference to this mock: panter/vue-i18next/src/i18n.js

Upvotes: 3

Related Questions