【发布时间】:2021-06-06 11:34:56
【问题描述】:
我正在尝试使用 Jest 来测试我的代码。在我尝试从测试中排除一个类方法之前,它工作得很好。
querySelector() 调用是我想跳过此方法进行测试的原因(“文档”显然为空,除非我在浏览器中运行脚本)
我试过这个解决方案,似乎是最推荐的一个:
/* istanbul ignore next */
appendNewInputFields() {
const howMany = Number(document.querySelector('#items-to-add').value);
[...Array(howMany)].forEach( i => {
const newInputField = this.createNewItemInputField();
this.inputItemsContainerNode.append(newInputField);
});
}
但测试一直失败,/* istanbul ignore next */ 行似乎被忽略了。
我也尝试将注释放在函数签名和它的主体之间(正如这里某处建议的那样),但没有运气:
FAIL js/DOMManager.test.js
● Test suite failed to run
TypeError: Cannot read property 'value' of null
135 | appendNewInputFields() /* istanbul ignore next */ {
136 |
> 137 | const howMany = Number(document.querySelector('#items-to-add').value);
| ^
138 |
我读到过这可能与babel-plugin-istanbul 有关。我试过了
npm --save-dev uninstall babel-plugin-istanbul
在终端返回:
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.3.2 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.3.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
removed 18 packages and audited 521 packages in 2.178s
但文件夹 babel-plugin-istanbul 仍然存在于我的工作文件夹内的 /node_modules/ 中,并且测试一直失败,好像没有任何变化。
如果我注释掉函数的主体,其他测试套件可以完美运行。如果我尝试将 ignore next 命令应用于代码的任何其他部分,则测试通过就好了,该行将被完全忽略。
如果我尝试手动删除 /babel-plugin-istanbul/ 文件夹(从我的工作文件夹中的 /node_modules/ 删除),Jest 将停止工作。
(这是我第一次安装 Node.js,我这样做只是因为我想用 Jest 开始单元测试。我指出这一点是因为这是我走出原版世界的第一步。我不知道如何处理 Node.js 和 npm,我刚刚启动了几个命令来安装它,我为 Jest 编写了一些测试,它们都立即运行良好。我没有使用任何其他框架,我尽量坚持原版 JS。)
----------------------- 编辑:
我尝试将代码更改为:
appendNewInputFields() {
// TODO solve the istanbul ignore issue
let howMany;
/* istanbul ignore if */
if(document != null) {
howMany = Number(document.querySelector('#items-to-add').value);
[...Array(howMany)].forEach( i => {
const newInputField = this.createNewItemInputField();
this.inputItemsContainerNode.append(newInputField);
});
console.log("added " + howMany + " input fields");
}
}
我不断得到
FAIL js/DOMManager.test.js
● Test suite failed to run
TypeError: Cannot read property 'value' of null
139 | /* istanbul ignore if */
140 | if(document != null) {
> 141 | howMany = Number(document.querySelector('#items-to-add').value);
| ^
142 |
143 | [...Array(howMany)].forEach( i => {
144 | const newInputField = this.createNewItemInputField();
在这一点上我完全一无所知。鉴于条件,“文档”应该为空,并且该块完全跳过,但它一直未能通过测试。
相同的代码在浏览器中运行时完全符合预期。
【问题讨论】:
标签: javascript node.js jestjs istanbul