我正在尝试利用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文件,自然会出错。