我已经为NodeJS应用程序编写了自定义ESLint规则。该规则按预期工作。但是,我在根据自定义规则运行单元测试时遇到了问题。
我遵循ESlint的文档来编写RuleTester,这实际上是一个 Mocha 单元测试用例。下面给出的是我的测试用例代码。
const { RuleTester } = require("eslint");
const rule = require("../../../lib/rules/chai-expect");
const ruleTester = new RuleTester();
ruleTester.run("chai-expect", rule, {
valid: [
{
code: "chai.expect(result).to.have.status(200);"
}
],
invalid: [
{
code: "expect(result).to.have.status(200);",
errors: [
{
message: "chai.expect() should be used for assertions in test cases."
}
]
},
{
code: "result.should.have.status(200);",
errors: [
{
message: "chai.expect() should be used for assertions in test cases."
}
]
},
{
code: "should(result).have.status(200);",
errors: [
{
message: "chai.expect() should be used for assertions in test cases."
}
]
}
]
});
我为有效提供了一种方案,为无效情况提供了三种方案。测试用例适用于有效用例。对于无效情况,在这三种情况下都会出现以下错误。
1) chai-expect invalid expect(result).to.have.status(200): AssertionError [ERR_ASSERTION]: Should have 1 error but had 0: [] + expected - actual -0 +1 at testInvalidTemplate (/node_modules/eslint/lib/testers/rule->tester.js:468:24) at Context.RuleTester.it (/node_modules/eslint/lib/testers/rule->tester.js:584:25)
我已经调试了该错误,并在ESLint库中引发了该块抛出错误。
assert.strictEqual(
messages.length, item.errors.length,
util.format(
"Should have %d error%s but had %d: %s",
item.errors.length, item.errors.length === 1 ? "" : "s", messages.length, util.inspect(messages)
)
);
项目表示测试用例中来自 invalid 块的对象。我无法弄清楚消息在这里代表什么。我得到了一个空白数组。