单元测试i18Next - TypeError:无法读取未定义的属性'init'

问题描述 投票:0回答:2

我的代码工作正常,但我有问题设置单元测试并测试它。当有使用i18next库的代码时出错,有人可以提供一些建议吗?

以下配置来自here

错误

TypeError:无法读取undefined的属性'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');        
})

模拟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/*"]            
        }
    } 
}
reactjs typescript unit-testing jestjs i18next
2个回答
0
投票

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

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

细节

问题中的模拟设置为使用i18next像这样:

import i18next from 'i18next';

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

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


0
投票

有人可以给出建议吗?我还是很困惑!更改此行后错误消失了

import i18next from 'i18next';

import * as i18next from 'i18next';
© www.soinside.com 2019 - 2024. All rights reserved.