jscoverage 必须指定encoding参数
由于代码越来越多,在进行代码覆盖测试的时候,经常出现jscoverage后的代码跑的测试不正确。 在排除各种干扰后发现,jscoverage对非ascii字符串转换不正确,导致test cases失败了。
重现问题
例如代码 ./foo/index.js
exports.getName = function getName() {
return '你好';
};
进行转换
$ jscoverage foo foo_cov
得到
/* automatically generated by JSCoverage - do not edit */
if (typeof _$jscoverage === 'undefined') _$jscoverage = {};
if (! _$jscoverage['index.js']) {
_$jscoverage['index.js'] = [];
_$jscoverage['index.js'][2] = 0;
_$jscoverage['index.js'][3] = 0;
}
_$jscoverage['index.js'][2]++;
exports.getName = (function getName() {
_$jscoverage['index.js'][3]++;
return "\u00e4\u00bd\u00a0\u00e5\u00a5\u00bd";
});
_$jscoverage['index.js'].source = ["","exports.getName = function getName() {"," return '你好';","};"];
明显看到 '你好'
被转换的编码出现错误了 "\u00e4\u00bd\u00a0\u00e5\u00a5\u00bd"
于是猜测 jscoverage
估计有指定编码的参数
$ jscoverage -h
Usage: jscoverage SOURCE-DIRECTORY DESTINATION-DIRECTORY
Instrument JavaScript with code coverage information.
Options:
--encoding=ENCODING assume .js files use the given character encoding
--exclude=PATH do not copy PATH
--js-version=VERSION use the specified JavaScript version
--no-highlight do not perform syntax highlighting
--no-instrument=PATH copy but do not instrument PATH
-v, --verbose explain what is being done
-h, --help display this help and exit
-V, --version display version information and exit
果然不出所料, encoding
能指定文件的编码
于是重现转换
$ jscoverage --encoding=utf-8 foo foo_cov_utf8
得到的文件编码终于正确了
/* automatically generated by JSCoverage - do not edit */
if (typeof _$jscoverage === 'undefined') _$jscoverage = {};
if (! _$jscoverage['index.js']) {
_$jscoverage['index.js'] = [];
_$jscoverage['index.js'][2] = 0;
_$jscoverage['index.js'][3] = 0;
}
_$jscoverage['index.js'][2]++;
exports.getName = (function getName() {
_$jscoverage['index.js'][3]++;
return "\u4f60\u597d";
});
_$jscoverage['index.js'].source = ["","exports.getName = function getName() {"," return '你好';","};"];
可以看到 '你好'
被正确转换成 "\u4f60\u597d"
验证脚本
jscoverage-must-set-encoding.js
:
var foo = require('./foo');
var foo_cov = require('./foo_cov');
var foo_cov_utf8 = require('./foo_cov_utf8');
console.log('foo', foo.getName(), foo.getName() === '你好');
console.log('foo_cov', foo_cov.getName(), foo_cov.getName() === '你好');
console.log('foo_cov_utf8', foo_cov_utf8.getName(), foo_cov_utf8.getName() === '你好');
输出:
foo 你好 true
foo_cov ä½ å¥½ false
foo_cov_utf8 你好 true
有爱
推荐阅读: Setting up Mocha & JSCoverage
^_^ 希望本文对你有用.