如何为Jest正确模拟i18n

时间:2019-01-16 08:58:24

标签: reactjs react-native mocking jestjs i18next

我在react-native中有一个容器,该容器正在导入通常存储在utils目录中的典型类型的函数,例如capitaliseWord()等。

utils模块的功能之一使用t,因此我们将i18n导入该utils文件夹中以便能够使用t

我们在languageDetector中使用i18n来检测用户的移动语言。因为languageDetector需要deviceLocale(例如英国,美国,荷兰等),并且Jest在不同的上下文中运行,所以如果我尝试测试容器,我将得到Cannot read property 'deviceLocale' of undefined。 / p>

因此,我创建了一个手动__mocks__目录(如https://jestjs.io/docs/en/manual-mocks#mocking-user-modules所示),并且创建了自己的i18n,该目录仅手动注入了deviceLocale字符串,以便能够运行测试。

结果是测试忽略了__mocks__/i18n并直接指向原始测试...关于测试可能会出错的任何想法?

还有package.json中我开玩笑的配置 https://gist.github.com/e00dd4ee41b06265632d3bcfe76e7cb0

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

嘲笑i18n.js https://gist.github.com/pavilion/17e322340581fb948ed7e319ae4a5ac9(注意detect中的languageDetector键已被手动模拟)

要测试的组件 https://gist.github.com/pavilion/20dc0c5b1a6d2ee709b7a71ec7b819c1

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

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

错误: https://gist.github.com/pavilion/012ee0889ebbe2b93b2108d93543e19c

1 个答案:

答案 0 :(得分:1)

我认为问题不在于模拟,而在于导入!在注入模拟之后,尝试这次需要测试中的组件:

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();
  });
});

我在本地尝试过,并且运行良好:该模块被嘲笑了。我简化了示例,也许您会遇到一些新错误,但是从技术上讲,这应该可以解决您的问题。

编辑:如果需要帮助,请将我的工作示例推送到github here

相关问题