4

在我的 TypeScript 项目中,我将像这样加载我的翻译文件:

const translations: any = {};
Object.keys(LOCALES).forEach(locale => {
  PARTS.forEach(part => {
    translations[locale] = merge(translations[locale], require(`./assets/i18n/${locale}/${part}.json`));
  });
});

这在使用 webpack 提供页面时效果很好。但是在我使用 Karma 进行的单元测试中,我使用karma-typescript了上面的代码会给出错误:

{
  "message": "Uncaught Error: Can't find ./assets/i18n/en_US/common.json [undefined] (required by .../src/config/translate.ts)\nat node_modules/karma-typescript/src/client/commonjs.js:13:17\n

我看过这个测试,似乎我在做正确的事情。

我的tsconfig.json

{
  "compilerOptions": {
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "forceConsistentCasingInFileNames": true,
    "lib": ["es2015", "dom"],
    "module": "commonjs",
    "noImplicitAny": false,
    "noImplicitReturns": true,
    "noImplicitThis": false,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "removeComments": false,
    "skipLibCheck": true,
    "sourceMap": true,
    "strictFunctionTypes": true,
    "strictNullChecks": true,
    "strictPropertyInitialization": false,
    "target": "es5"
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}

我的karma.conf.ts

module.exports = (config) => {
  config.set({
    basePath: './',
    frameworks: [
      'jasmine',
      'karma-typescript'
    ],
    plugins: [
      'karma-jasmine',
      'karma-typescript',
      'karma-ng-annotate-preprocessor',
      'karma-coverage',
      'karma-chrome-launcher'
    ],
    reporters: [
      'progress',
      'coverage'
    ],
    proxies: {
      '/assets/images': '/base/src/public/assets/images'
    },
    files: [
      'src/public/assets/images/**/*.png',
      'node_modules/jquery/dist/jquery.js',
      'node_modules/jasmine-jquery/lib/jasmine-jquery.js',
      'src/helper.spec.ts',
      'src/**/*.ts'
    ],
    preprocessors: {
      'src/**/!(*spec).ts': ['karma-typescript', 'ng-annotate', 'coverage'],
      'src/helper.spec.ts': ['karma-typescript'],
      'src/**/*spec.ts': ['karma-typescript']
    },
    karmaTypescriptConfig: {
      tsconfig: './tsconfig.json',
      bundlerOptions: {
        transforms: [
          require('karma-typescript-es6-transform')()
        ]
      }
    },
    coverageReporter: {
      dir: 'coverage/',
      reporters: [{
        type: 'text-summary',
        subdir: 'reports'
      }, {
        type: 'html',
        subdir: 'reports'
      }],
      check: {
        global: {
          statements: 80,
          branches: 50,
          functions: 75,
          lines: 80
        }
      }
    },
    browsers: [
      'ChromeNoSandboxHeadless'
    ],
    customLaunchers: {
      ChromeNoSandboxHeadless: {
        base: 'Chrome',
        flags: [
          '--no-sandbox',
          // See https://chromium.googlesource.com/chromium/src/+/lkgr/headless/README.md
          '--headless',
          '--disable-gpu',
          // Without a remote debugging port, Google Chrome exits immediately.
          '--remote-debugging-port=9222',
        ]
      }
    },
    singleRun: true
  });
};

还有我的依赖:

"devDependencies": {
  "awesome-typescript-loader": "^3.4.1",
  "jasmine-core": "^2.99.1",
  "jasmine-reporters": "^2.3.0",
  "jasmine-spec-reporter": "^4.2.1",
  "karma": "^2.0.0",
  "karma-chrome-launcher": "^2.2.0",
  "karma-coverage": "^1.0.0",
  "karma-jasmine": "^1.0.2",
  "karma-ng-annotate-preprocessor": "0.0.1",
  "karma-sourcemap-loader": "^0.3.7",
  "karma-spec-reporter": "0.0.26",
  "karma-typescript": "^3.0.12",
  "karma-typescript-es6-transform": "^1.0.3",
  "ng-annotate-loader": "^0.6.1",
  "ts-node": "^5.0.1",
  "tslint": "^5.9.1",
  "typescript": "2.7.1",
  "webpack": "^3.11.0",
  ...
}

编辑 1:刚刚意识到这可能与导入动态模块有关,所以我重构了我的 require 代码,如下所示:

export const importTranslation = async (locale: string, part: string) => {
  return await import(/* webpackChunkName: "translations" */ `./assets/i18n/${locale}/${part}.json`);
};

这不会使 Karma 崩溃,但在运行测试时仍然给我一个错误:

HeadlessChrome 0.0.0 (Mac OS X 10.13.5) Config translate should load the translations FAILED
    Error: Can't find ./assets/i18n/en_US/common.json [undefined] (required by [...]/src/config/translate.ts)
        at require (node_modules/karma-typescript/src/client/commonjs.js:13:23)
        at node_modules/karma-typescript/src/client/commonjs.js:18:24
        at src/config/translate.ts:18:9 <- src/config/translate.js:9:9010
4

0 回答 0