node.js - 测试 Grunt 任务

标签 node.js gruntjs mocha.js yeoman

我正在使用 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/

相关文章:

node.js - Chai 测试 TypeError : Converting circular structure to JSON

node.js - 如何在 Node 中运行 PAC 代理脚本?

javascript - 通过 Firebase 功能发送时 FCM 出现高延迟

node.js - 如何使用sailsjs v0.10连接mongodb?

gruntjs grunt-init grunfile 抛出错误 fatal error : Arguments to path. join 必须是字符串

javascript - mocha with nodejs assert 挂起/超时为 assert(false) 而不是错误

node.js - typescript :按值或按引用传递

javascript - 当 ngAnnotate 说 "Cannot create property ' $methodName' 时,这是什么意思...”

node.js - 循环中的 Node Grunt 异步任务,闭包不起作用

session - SailsJs::与 mocha 保持 session