我可以在我的 ecmascript-6 应用程序中使用 mocha 对反应模板进行单元测试吗?

Can I use mocha to unit test react-templates in my ecmascript-6 app?

我已经在 ecmascript-6 应用程序中用 react-templates 替换了我所有的 React jsx。我真的很喜欢将 html 模板放在专用的 .rt 文件中,而不是与 es6 代码混在一起; jsx 似乎是错误的。

我在开发中使用 webpack-dev-server。我必须在 preLoader 步骤中将 .rt 转换为 es6 才能使其正常工作,然后常规的 es6-to-commonjs babel 加载程序对结果进行操作。 Webpack 在开发和生产中运行良好。 webpack -p 将所有内容编译并缩小为用于生产构建的 commonjs 块。目前还好。

这是我在 webpack.config.js 中的功能模块加载器配置:

...
  module: {
    preLoaders: [{
      test: /\.rt$/,
      loader: 'react-templates?modules=es6'
    }],
    loaders: [{
      test: /\.jsx?$|\.rt$/,
      loader: 'babel'
    }, {
      test: /\.scss$/,
      loader: ExtractTextPlugin.extract('style', ['css', 'sass?sourceMap'])
    }]
  },
...

这里是问题开始的地方——我有 mocha 单元测试与 jsx 组件一起工作,但我似乎无法获得与 运行 相同的单元测试,因为我正在使用 react-templates。

Mocha 会使用特殊的 --compiler 将 es6 js 编译为 commonjs,但我唯一能找到的反应模板和 mocha 是一个硬编码的模块 mocha-react-templates-compiler,可以将模板直接转换为commonjs,不是 es6.

所以,在我的 es6 中像这样的行:

import MyComponentRT from './MyComponent.rt'

在开发和生产中表现出色,但在 mocha 测试中表现出色。

我试过了:

mocha --recursive --compilers rt:mocha-react-templates-compiler,js:babel-register ./js/test

但我得到的错误明显与 es6 代码相关,期望 rt 文件也是 es6。颠倒编译器顺序没有帮助。

是否有人在同一个项目中使用 react-templates 和 es6 和 mocha?你是如何获得 运行 的 mocha 测试的?

我最终用 gulp 解决了这个问题。

我使用 gulp 将 .rt 文件显式编译为 es6,然后将 es6 编译为 .rt.js,类似于 webpack 的配置。所有输出文件都转储到临时 "testbuild" 文件夹中,然后对 .js 文件执行相同操作,mocha 可以从那里 运行 进行测试。

gulpfile.js:

var gulp = require('gulp');
var clean = require('gulp-clean');
var rt = require('gulp-react-templates');
var babel = require('gulp-babel');

var testbuild_dir = 'testbuild';

gulp.task('clean', function() {
  return gulp.src(testbuild_dir, {read:false}).pipe(clean());
});

gulp.task('buildrt', ['clean'], function() {
  return gulp.src('src/js/**/*.rt')
    .pipe(rt({modules: 'es6'}))
    .pipe(babel({presets: ['es2015']}))
    .pipe(gulp.dest(testbuild_dir));
});

gulp.task('buildjs', ['buildrt'], function() {
  return gulp.src('src/js/**/*.js')
    .pipe(babel({presets: ['es2015','react']}))
    .pipe(gulp.dest(testbuild_dir));
});

gulp.task('testbuild', ['buildjs']);

package.json 脚本:

  "scripts": {
    "dev": "webpack-dev-server --content-base /build --inline --devtool source-map --host 0.0.0.0",
    "build": "webpack -p",
    "test": "npm run testbuild && npm run testartifacts && npm run testclean",
    "testbuild": "gulp testbuild",
    "testartifacts": "mocha --recursive ./testbuild/js/test",
    "testclean": "gulp clean"
  },

现在我可以 运行 npm run test 一切正常!