我正在使用 Yeoman 生成一些项目和 grunt 任务。 现在我也想使用 Mocha 测试生成的 grunt 任务,但我只找到一些如何在 Grunt 中使用 Mocha 测试的信息;-)
有人可以帮忙吗?
最佳答案
这不是一个优雅的解决方案,但我采取了安装依赖项(npm install
)并随后运行相应的 grunt 任务(例如 grunt less
)的方法,然后在该操作后编写测试逻辑。我使用过嵌套 exec呼吁这样做。
describe('less grunt tasks tests', function () {
var prompts = {
workFolder: 'temp',
fiddleDesc: 'mocha test'
};
var testGlobal = {};
beforeEach(function(done) {
testGlobal.app = helpers.run(path.join(__dirname, '../app'))
.inTmpDir(function(dir, err) {
if(err) { done(err); return; }
testGlobal.dir = dir;
// console.log(dir);
})
.withArguments(['skip-install'])
.withOptions({ less: true })
.withPrompts(prompts)
.on('end', function(){
done();
});
});
it('should modify app/styles/style.css', function(done){
this.timeout(60000 * 10); //10 minutes - my network is f**ked up
var opts = {
cwd : testGlobal.dir,
env: process.env,
detached: true
};
var gen = testGlobal.app.generator;
var devdeps = gen.devDependencies.join(' ');
var rootPath = testGlobal.dir;
var getPath = function(fpath) {
var s = path.join(rootPath, fpath);
// console.log(s); ;
return s;
};
exec('npm install ' + devdeps, opts, function(err, stdout, stderr) {
if(err) {
done(err);
return;
}
var h1 = fs.readFileSync(getPath('app/less/h1.less'), 'utf8');
var css = fs.readFileSync(getPath('app/styles/style.css'), 'utf8');
// expect(css).to.not.contain(h1);
expect(css).to.not.contain('h1');
exec('grunt less', opts, function(e, out, serr){
if(e) {
done(e);
return;
}
// console.log(out);
var h1 = fs.readFileSync(getPath('app/less/h1.less'), 'utf8');
var css = fs.readFileSync(getPath('app/styles/style.css'), 'utf8');
// expect(css).to.contain(h1); //this expect fails since for some reason \r are stripped out
expect(css).to.contain('h1');
done();
});
});
});
});
如需更多引用,您可以在 repo 中查看更多测试代码我反对。
Ps:非常感谢您对我所采取的方法提出评论。
关于node.js - 测试 Grunt 任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26214023/