简体   繁体   English

如何使用Mocha对CodeEval的JS代码进行单元测试?

[英]How to unit test JS code for CodeEval using Mocha?

I would like to unit test my JavaScript solution for a challenge on the CodeEval site using Mocha framework. 我想使用Mocha框架在CodeEval网站上对JavaScript解决方案进行单元测试以应对挑战。

I could create separate files or use some other fancy approach, but: 我可以创建单独的文件或使用其他一些花哨的方法,但是:

  • I want my solution to be ready to upload just after unit tests pass, without any files changes (that I could forgot to do). 我希望我的解决方案可以在单元测试通过后立即上传,而无需更改任何文件(我可能会忘记这样做)。
  • Additional code should not introduce unnecessary time or memory usage. 附加代码不应引入不必要的时间或内存使用量。

But CodeEval requirements and Mocha seem incompatible together, or not? 但是CodeEval要求和Mocha似乎不兼容?

Default CodeEval stub: 默认的CodeEval存根:

var fs  = require("fs");
fs.readFileSync(process.argv[2]).toString().split('\n').forEach(function (line) {
if (line != "") {
    //do something here
    console.log(answer_line);
}

It's quite simple to check numbers of parameters of the program. 检查程序的参数数量非常简单。 With CodeEval it will be 3, with mocha it will be 2. Mocha execution always falls into "else" and exports the logic function. 使用CodeEval时,它将为3;使用Mocha时,它将为2。Mocha执行总是落入“其他”并输出逻辑函数。

Tested solution. 经过测试的解决方案。

var fs  = require("fs");

module.exports = processLine;

if (process.argv.length === 3) {
    // codeeval mode
    fs.readFileSync(process.argv[2]).toString().split('\n').forEach(function (line) {
        if (line != "") {
            console.log(processLine(line));
        }
    });
}

function processLine(line) {
    return line;
}

Remarks: 备注:

  • It won't work if mocha is run with parameters nor with mocha.opts file, unless there's more then 3 parameters; 如果同时使用参数和mocha.opts文件运行mocha,将无法正常工作,除非有3个以上的参数。
  • setting module.exports inside the files doesn't bother CodeEval. 在文件内部设置module.exports不会影响CodeEval。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM