React组件的Angular-cli测试

时间:2018-07-01 10:56:06

标签: angular reactjs angular-cli karma-jasmine karma-runner

我有一个包含试剂成分的应用程序,我已经实现了这些成分与整个应用程序一起编译。现在,我想配置karma来测试React组件。

Angular 6 +

但是我遇到了React个组件的错误

Uncaught Error: Module parse failed: Unexpected token (32:3)
  You may need an appropriate loader to handle this file type.
  |             expect(props instanceof Object).toBeTruthy();
  |             const component = ReactTestUtils.renderIntoDocument(
  |                     <Slider
  |                     currentItem={props.currentItem}
  |                     items={props.items}

karma.conf.js

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma')
    ],
    client: {
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      dir: require('path').join(__dirname, '../coverage'),
      reports: ['html', 'lcovonly'],
      fixWebpackSourcePaths: true
    },
    angularCli: {
      environment: 'dev'
    },
    module: {
        loaders: [
         { test: /\.js$/, loader: 'babel-loader' }
        ]
    },
    reporters: ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  });
};
为spec.js添加了

test.ts

// This file is required by karma.conf.js and loads recursively all the .spec and framework files

import 'zone.js/dist/zone-testing';
import { getTestBed } from '@angular/core/testing';
import {
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';

declare const require: any;

// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting()
);
// Then we find all the tests.
const context = require.context('./app/modules/visualization/social-sites/', true, /\.spec\.(j|t)s$/);
// And load the modules.
context.keys().map(context);

.babelrc

{
  "presets": [
    ["env", {
      "targets": {
        "chrome": 53,
        "browsers": ["last 2 versions", "safari 7"]
      },
      "modules": false,
      "loose": true
    }],
    "react"
  ],
  "plugins": ["transform-decorators-legacy", "transform-class-properties", "transform-object-rest-spread"],
  "env": {
    "production": {
      "presets": [
        "babili"
      ]
    },
    "test": {
      // bacause of earlier we disable transformation of es2015 modules (needed for jest)
      "presets": ["env", "react"],
      "plugins": ["transform-es2015-modules-commonjs"]
    }
  }
}

1 个答案:

答案 0 :(得分:0)

似乎您应该用babel配置babel-preset-react或在模块加载程序部分的jsx-loader旁边添加babel-loader