【问题标题】:Unit test i18Next - TypeError: Cannot read property 'init' of undefined单元测试 i18Next - TypeError:无法读取未定义的属性“init”
【发布时间】:2019-09-16 14:25:52
【问题描述】:

我的代码工作正常,但我在设置单元测试和测试它时遇到了问题。有代码使用 i18next 库时出现错误,谁能给点建议?

以下配置来自here

错误

TypeError: 无法读取未定义的属性“init”

   7 |  i18next
>  8 |   .init({
     |    ^
   9 |     interpolation: {
  10 |       escapeValue: false,
  11 |     },

Helper.tsx

export function validation(controlName: string){   
    var messages = require('src/translations/i18next');
    var requireMessage=messages.t('required');
    //omit irelevant code
  }

Helper.test.tsx

test('Validation',()=>{
    expect(Helper.validation('My Name')).toBe('aaaaa');        
})

mock-setup.js

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

jest.config.js

module.exports = {
    verbose: true,
    'roots': [
      '<rootDir>/src'
    ],
    'transform': {            
      "^.+\\.(js)$": "<rootDir>/node_modules/babel-jest",
      "^.+\\.tsx?$": "ts-jest"
    },
    'testRegex': '(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$',    
    'moduleFileExtensions': [
      'ts',
      'tsx',
      'js',
      'jsx',
      'json',
      'node'
    ],
    'moduleNameMapper': {
      '^src/(.*)': '<rootDir>/src/$1',
      '^components/(.*)': '<rootDir>/src/components/$1'
    },
    'snapshotSerializers': ['enzyme-to-json/serializer'],

    'setupFiles': ['<rootDir>/src/jest/setupEnzyme.ts',
    '<rootDir>/src/jest/mock-setup.js', 
  ],
     'moduleDirectories': ['node_modules', 'src']
  }

i18next.tsx

import i18next from 'i18next';

var common_en = require( "src/translations/en/common.json");
var common_es = require( "src/translations/es/common.json");

i18next
  .init({
    interpolation: {
      escapeValue: false,
    },
    lng: 'en', // 'en' | 'es'
    resources: {
      en: {translation: common_en},
      es: {translation: common_es},
    },
    debug: true,
  })

  export default i18next;

tsconfig.json

{
    "compilerOptions": {
        "lib": [ "es2015","dom" ],
      "target": "es5",
      "module": "commonjs",
      "esModuleInterop": true,
      "jsx": "react",   
      "sourceMap":  true, 
      "baseUrl": ".",
      "allowSyntheticDefaultImports": true,
        "paths": {
            "src/*": ["src/*"],
            "components/*": ["src/components/*"]            
        }
    } 
}

【问题讨论】:

  • 你能分享src/translations/i18next的代码吗? (看起来它调用i18next.init(...) 而不是i18next.use(...).init(...)
  • 更新问题,是的,我正在使用 i18next.init。你的意思是不正确吗?
  • 你解决了吗?

标签: reactjs typescript unit-testing jestjs i18next


【解决方案1】:

看起来你应该像这样模拟i18next

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

详情

问题中的模拟设置为使用i18next,如下所示:

import i18next from 'i18next';

i18next
  .use(...)
  .init(...);

由于你没有使用.use,你可以直接模拟.init

【讨论】:

  • 如果这些信息足以修复它,请告诉我。您可能还需要在 TypeScript 配置中设置 esModuleInterop 并更改您的要求(我很惊讶您不需要像这样要求 defaultvar messages = require('src/translations/i18next').default;
  • 应用您提供的解决方案后仍然遇到同样的问题。甚至在 tsconfig 中设置 esModuleInterop:true。用 tsconfig.json 更新了问题。没有默认就可以正常工作
【解决方案2】:

任何人都可以就此提供建议吗?我还是一头雾水!我更改此行后错误消失了

import i18next from 'i18next';

import * as i18next from 'i18next';

【讨论】:

    猜你喜欢
    • 2021-09-28
    • 2020-01-17
    • 2018-04-18
    • 2018-11-11
    • 2021-01-22
    • 1970-01-01
    • 2019-08-06
    • 2015-08-27
    • 1970-01-01
    相关资源
    最近更新 更多