Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly mock i18n for Jest

I have a container in react-native that is importing the typical kind of function that we usually store at utils directory such as capitaliseWord() or whatever.

One of the functions of that utils module uses t, so we import i18n inside that utils folder in order to be able to use t

We use languageDetector inside our i18n to detect the user's mobile language. Because languageDetector needs deviceLocale (e.g UK, US, NL, etc), and Jest runs on a different context, if I try to do test the container, I will get Cannot read property 'deviceLocale' of undefined.

So I created a manual __mocks__ directory (as https://jestjs.io/docs/en/manual-mocks#mocking-user-modules states) and I created my own i18n that just injects the deviceLocale string manually, in order to be able to run the tests.

Turns out the test ignores the __mocks__/i18n and points directly to the original one... Any ideas of what it could go wrong?

And my jest config inside package.json https://gist.github.com/e00dd4ee41b06265632d3bcfe76e7cb0

original i18n.js https://gist.github.com/pavilion/3c48c6017a82356914f0ad69d7251496

mocked i18n.js https://gist.github.com/pavilion/17e322340581fb948ed7e319ae4a5ac9 (notice the detect key inside languageDetector has been manually mocked)

Component to be tested https://gist.github.com/pavilion/20dc0c5b1a6d2ee709b7a71ec7b819c1

utils.js https://gist.github.com/pavilion/1c5df0f71d50462d75234365ae1e4aaf

Comp.test.js https://gist.github.com/pavilion/2a84880bee3a99fa51fc3e28cfa8f913

Error: https://gist.github.com/pavilion/012ee0889ebbe2b93b2108d93543e19c

like image 742
ismael oliva Avatar asked Nov 16 '25 00:11

ismael oliva


1 Answers

I think the problem is not in the mock, but the import! Try this time requiring the component in the test, after the mock has been injected:

import React from 'react';
import { shallow } from 'enzyme';

jest.mock('../../config/i18n');

describe('<Comp />', () => {
  it('must match the snapshot', () => {
    // Require here instead of importing on top
    const Comp = require("./Comp").default;

    // state and props properly set up
    const wrapper = shallow(<Comp />);
    expect(wrapper).toMatchSnapshot();
  });
});

I tried this locally and it's working fine: the module gets mocked. I simplified a lot my example so perhaps you run into some new error but technically this should solve your problem.

EDIT: pushed my working example to github here in case it's for any help.

like image 189
josemigallas Avatar answered Nov 17 '25 20:11

josemigallas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!