尝试使用mocha、babel和es6模块设置测试

4

我正在尝试利用grunt和babel将我的es6源文件作为给定测试的依赖项进行加载。因此,我一直在通过browserify运行实际的src并编译应用程序:

module.exports = function (grunt) {

  // Import dependencies
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-browserify');

  grunt.initConfig({
    browserify: {
      dist: {
        files: {
          'www/js/bundle.js': ['src/app.js'],
        },
        options: {
          transform: [['babelify', { optional: ['runtime'] }]],
          browserifyOptions: {
            debug: true
          }
        }
      }
    },
    jshint : {
      options : {
        jshintrc : ".jshintrc",
      },

      dist: {
        files: {
          src: ["src/**/*.js"]
        }
      }
    },
    watch: {
      scripts: {
        files: ['src/**/*.js'],
        tasks: ['jshint', 'browserify'],
        options: {
          atBegin: true,
          spawn: true
        },
      },
    }
  });

  grunt.registerTask("default", ['watch']);

};

它会编译成一个单独的bundle.js文件,我将其包含在我的index.html文件中。很棒!

所以我想从测试中导入正在测试的文件。因此,我有一个简单的存储对象叫做InteractionStore,位于src/stores/interaction_store.js。然后我创建了一个规范文件:test/stores/interaction_store_spec.js

import expect from "expect.js";
import InteractionStore from '../../../src/stores/interaction_store.js';

describe("InteractionStore", () => {
  beforeEach(() => {
    InteractionStore.data = [];
  });
  describe("#start()", () => {
    it ("should apped multiple", function () {
      InteractionStore.start();
      InteractionStore.start();
      InteractionStore.start();
      expect(InteractionStore.data.length).toEqual(3);
    });
  });
});

所以我直接导入商店。 我已经为测试过程添加了一些部分到grunt文件中:

module.exports = function (grunt) {

  // Import dependencies
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-browserify');
  grunt.loadNpmTasks('grunt-contrib-sass');
  grunt.loadNpmTasks('grunt-mocha-test');
  grunt.loadNpmTasks('grunt-babel');

  grunt.initConfig({
    babel: {
      options: {
        sourceMap: true,
        modules: "common"
      },
      test: {
        files: [{
          expand: true,
          cwd: 'test',
          src: ['**/*.js'],
          dest: 'test/compiled_specs',
          ext:'.js'
        }]
      }
    },
    browserify: {
      dist: {
        files: {
          'www/js/bundle.js': ['src/app.js'],
        },
        options: {
          transform: [['babelify', { optional: ['runtime'] }]],
          browserifyOptions: {
            debug: true
          }
        }
      }
    },
    clean: ["test/compiled_specs"],
    jshint : {
      options : {
        jshintrc : ".jshintrc",
      },

      dist: {
        files: {
          src: ["src/**/*.js"]
        }
      }
    },
    watch: {
      scripts: {
        files: ['src/**/*.js'],
        tasks: ['jshint', 'browserify:dist'],
        options: {
          atBegin: true,
          spawn: true
        },
      },
    },

    mochaTest: {
      test: {
        src: ['test/compiled_specs/**/*_spec.js']
      }
    }
  });

  grunt.registerTask("default", ['watch']);
  grunt.registerTask("test", ['clean', 'babel', 'mochaTest']);

};

Babel可以编译测试,但运行时会加载仍处于es6状态的src文件夹中的.js文件,自然会出错。
1个回答

3

在Reddit的帮助下,我成功解决了原来的问题。与其使用mocha测试,我会直接运行mocha命令:

mocha --ui tdd --compilers js:babel/register test/**/*.js

你可以轻松地将其添加为npm脚本。

由于我正在测试cordova项目,因此我需要phantom js。这也需要一些解决方案,从这里的gist中获得了很多帮助:https://gist.github.com/nmabhinandan/6c63463d9f0987020c6f。但是这是我的最终设置,如果有人感兴趣:

文件夹结构:

src/
  -- app code
test/
  spec/
    stores/
      interaction_store_spec
  SpecRunner.js
tests.html

module.exports = function (grunt) {

  // Import dependencies
  grunt.loadNpmTasks('grunt-contrib-watch')
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-browserify');
  grunt.loadNpmTasks('grunt-contrib-sass');
  grunt.loadNpmTasks('grunt-babel');
  grunt.loadNpmTasks('grunt-exec');
  grunt.loadNpmTasks('grunt-contrib-clean');

  grunt.initConfig({
    babel: {
      options: {
        sourceMap: true,
        modules: "amd"
      },
      test: {
        files: [{
          expand: true,
          src: ["test/**/*.js"],
          dest: "dist",
          ext: ".js"
        }, {
          expand: true,
          src: ["src/**/*.js"],
          dest: "dist",
          ext: ".js"
        }]
      }
    },
    browserify: {
      dist: {
        files: {
          'www/js/bundle.js': ['src/app.js'],
        },
        options: {
          transform: [['babelify', { optional: ['runtime'] }]],
          browserifyOptions: {
            debug: true
          }
        }
      }
    },
    clean: {
      test: ["dist/test"]
    },
    eslint : {
      target: ["src/**/*.js"]
    },
    exec: {
      run_tests: "node_modules/.bin/mocha-phantomjs -p $(which phantomjs) tests.html"
    },
    sass: {
      dist: {
        options: {
          style: 'compressed'
        },
        files: {
          'www/css/styles.css': 'www/css/sass/styles.scss'
        }
      }
    },
    watch: {
      css: {
        files: ['www/css/sass/*.scss'],
        tasks: ['sass']
      },
      scripts: {
        files: ['src/**/*.js'],
        tasks: ['eslint', 'browserify:dist'],
        options: {
          atBegin: true,
          spawn: true
        },
      },
    }
  });

  grunt.registerTask("default", ['sass','watch']);
  grunt.registerTask("test", ["clean", "babel:test", "exec:run_tests"]);
};

重要的是要注意gruntfile中使用babel本身而不是browserify。我还添加了mocha-phantom和requirejs来支持测试。watch、sass和eslint仅用于构建源代码以运行应用程序。Babel将源代码和测试编译为AMD模块。在使用requirejs时,必须在导入字符串中删除扩展名。它适用于browserify,但如果有扩展名,则requirejs不会使用SpecRunner中的baseUrl。
SpecRunner.js:
// RequireJS configuration
require.config({
  baseUrl: 'dist/test',
  urlArgs: 'cb=' + Math.random(),
  paths: {
    spec: 'spec', // lives in the test directory
  },
  hbs: {
    disableI18n: true
  }
});

let testSuite = {
  specs: [
    'spec/stores/interaction_store_spec'
  ]
};

// run mocha
(function() {
  require(testSuite.specs, function() {

    if (window.mochaPhantomJS) {
      mochaPhantomJS.run();
    } else {
      mocha.run();
    }

  });
})();

Tests.html:

<!doctype html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Mocha Spec Runner</title>
    <link rel="stylesheet" href="node_modules/mocha/mocha.css">
</head>
<body>
    <div id="mocha"></div>

    <script src="node_modules/mocha/mocha.js"></script>
    <script src="node_modules/expect.js/index.js"></script>

    <script>
        mocha.ui('bdd');
        mocha.reporter('html');
    </script>
    <script src="node_modules/requirejs/require.js" data-main="dist/test/SpecRunner"></script>
</body>
</html>

json包:

{
  "name": "test",
  "version": "0.0.1",
  "devDependencies": {
    "babel": "^5.8.12",
    "babel-runtime": "^5.8.12",
    "babelify": "^6.1.3",
    "eslint": "^0.24.1",
    "expect.js": "^0.3.1",
    "grunt": "^0.4.5",
    "grunt-babel": "^5.0.1",
    "grunt-browserify": "^3.8.0",
    "grunt-contrib-clean": "^0.6.0",
    "grunt-contrib-watch": "^0.6.1",
    "grunt-eslint": "^16.0.0",
    "grunt-exec": "^0.4.6",
    "mocha": "^2.2.5",
    "mocha-phantomjs": "^3.6.0",
    "requirejs": "^2.1.20"
  }
}

当我运行grunt testgrunt babel时,更明确地说,我会在应用程序的根目录中获得一个dist文件夹:

 dist/
   test/
     -- compiled specs
   src/
     -- compiled source

然后PhantomJS可以正常运行这些规范测试。请注意,您需要通过homebrew或类似工具安装PhantomJS才能使其正常工作。我使用的版本是1.9.2。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接