Bjo*_*cus 7 javascript mocha.js
有时在运行一组 mocha 测试时,我并不关心失败的细节;我只想要一个通过或失败的测试列表。我试过几个记者,但他们似乎都输出失败的详细信息。我喜欢默认的规范报告结构,但我找不到如何隐藏细节。
这是一个说明性示例。对于这些测试:
const assert = require('assert')
describe('test test', function() {
it('should pass', function() {
})
it('should fail', function() {
assert(false)
})
})
Run Code Online (Sandbox Code Playgroud)
这给出了这样的输出:
test test
? should pass
1) should fail
1 passing (9ms)
1 failing
1) test test
should fail:
AssertionError [ERR_ASSERTION]: false == true
+ expected - actual
-false
+true
at Context.<anonymous> (test-solution.js:69:5)
Run Code Online (Sandbox Code Playgroud)
但我想要的只是这个:
test test
? should pass
1) should fail
1 passing (9ms)
1 failing
Run Code Online (Sandbox Code Playgroud)
我是否遗漏了一些明显的东西,或者这些细节不是我可以压制的?
小智 1
我也想隐藏这一点,对我来说,大多数默认记者似乎也不是那么好。每一条无用的线都会浪费我们的时间。在我看来,自定义输出应该非常简单。
\n构建自己的自定义报告器是您问题的正确答案。然而 - 因为这花了我很长时间 - 这里有一个非常简短且简单的替代方案:禁用报告器并记录事件。
\nconst Mocha = require(\'mocha\');\nlet file = \'./devtest.js\';\nlet passCount = 0;\nlet errors = [];\n\n// start with disabled reporter\nconst mocha = new Mocha({ reporter: function () {} });\nmocha.addFile(file);\nconsole.log(\'\\n===== start mocha file \' + file);\n\nmocha.run()\n .on(\'pass\', function (test) {\n passCount++;\n logSuccess(test.title);\n })\n .on(\'fail\', function (test, err) {\n errors.push({test, err});\n logError(test.title);\n })\n .on(\'end\', function () {\n console.log();\n console.log(\' -------------------------\');\n logSuccess(passCount + \' tests passed\');\n logError(errors.length + \' tests failed\');\n // do something here - like:\n // callback(errors)\n });\n\nfunction logSuccess (str) {\n console.log(\'\\u001b[32m \xe2\x9c\x93 \\u001b[0m\\u001b[90m\' + str + \'\\u001b[0m\');\n}\nfunction logError (str) {\n console.log(\'\\u001b[31m \xe2\x9c\x96 \' + str + \'\\u001b[0m\');\n}\n\nRun Code Online (Sandbox Code Playgroud)\n\n当然,与标准报告器相比,它的一些功能较少,但扩展非常简单 - 您拥有所有错误和数据。所以速度非常快。
\n也许其他人可以发布一个非常简单的工作示例,即自定义报告器 - 对我来说,自定义报告器破坏了我的控制台输出,并且我对更多调试不感兴趣。
\n