gpt4 book ai didi

gruntjs - 获得 grunt karma 来运行一个单元测试

转载 作者:行者123 更新时间:2023-12-04 02:07:25 26 4
gpt4 key购买 nike

我想知道是否有人有过grunt karma来运行一个在 watch 上改变的规范。这是我下面的配置。问题在于 grunt.config('karma.unit.options.files', filepath); 行似乎没有做任何事情,因为所有规范仍在运行,但是 foo 在 karma:unit:run 被触发之前确实获得了输出。

grunt.initConfig({
karma: {
unit: {
configFile: 'karma.conf.js',
background: true,
singleRun: false,
options: {
files: allFilesArray
}
}
},
watch: {
options: {
spawn: false,
livereload: true
},
karma: {
files: ['js/spec/**/*.spec.js', 'js/src/**/*.js'],
tasks: ['karma:unit:run']
}
}
})

grunt.event.on('watch', function (action, filepath){
console.log('foo');
grunt.config('karma.unit.options.files', filepath);
});

有没有人在文件更改时在终端中运行一个规范?我们有成千上万的测试,所以它开始变慢。

谢谢,
亚历克斯

最佳答案

我得到了这个工作。基本上,您可以使用带有事件处理程序的 watch 来在文件更改时动态更改 karma 配置。这是纲要:

我的 Grunt 配置有两个 karma 任务:“all”和“one”。 “all”运行所有这些,而“one”只运行一个它事先不知道的文件。

grunt.initConfig({
// ...
karma: {
all: {
configFile: 'karma.conf.js',
browsers: ['PhantomJS'],
singleRun: true,
options: {
files: [
'bower_components/jquery/dist/jquery.js', // dependencies
'src/js/**/*.js', // js source files
'src/js/**/*.spec.js' // unit test files
]
}
},
one: {
configFile: 'karma.conf.js',
browsers: ['PhantomJS'],
singleRun: true,
files: [
{src: 'bower_components/jquery/dist/jquery.js'}, // dependencies
{src: ['src/js/**/*.js','!src/js/**/*.spec.js']} // source files
// (exclude the unit test files)
// watchEventListener will add the unit test file to run
]
}
},
// ...
});

然后在我的 gruntfile 中,我添加了一个监听事件的监听器。此监听器更新 karma:one 任务并添加单元测试文件。我们保留原始 files 数组的副本,否则我们的添加将在 watch 任务的生命周期中持续存在并累积。
// when a unit test changes, execute only it
var original_karmaOne_files = grunt.config.get('karma.one.files'); // keep the original files array
grunt.event.on('watch', function watchEventListener(action, filepath, target){

// this handler handles ALL watch changes. Try to filter out ones from other watch tasks
if (target == 'js_spec') handleJSHintSpec();

// ---------------------
function handleJSHintSpec() {
if (action == 'deleted') return; // we don't need to run any tests when a file is deleted
// this will probably fail if a watch task is triggered with multiple files at once
// dynamically change the config
grunt.config.set('karma.one.files', [].concat(original_karmaOne_files, [{src: filepath}]));
}
});

这是我的 gruntfile 的监视任务:
watch: {
// ...
// when js spec files change,
// lint them
// run unit tests
js_spec: {
options: {
interrupt: true
},
files: 'src/js/**/*.spec.js',
tasks: ['jshint:js_spec', 'karma:one']
},
// ...
}

我的 karma.conf.js file 是非常默认的,但它的 files 数组是空的。实际上,我已将其注释掉,因此该属性未定义。
// list of files / patterns to load in the browser
//files: [], // specified in the gruntfile

关于gruntjs - 获得 grunt karma 来运行一个单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28108485/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com