如何增加分支覆盖在单元测试用例for循环与if条件?



我的测试Javascript文件"buildButtons.js">

let viewButtonList = [
{ buttonLink: "about", buttonLabel: "ABOUT" },
{ buttonLink: "contact", buttonLabel: "CONTACT" },
{ buttonLink: "prodcucts", buttonLabel: "PRODUCTS" },
{ buttonLink: "don't include", buttonLabel: "DON'T INCLUDE" }
]
let buttonList = []
let buildButtons = true
export function buildButtonList() {
for (let item of viewButtonList) {
if (buildButtons) {
buttonList.push(item)
}
}
return buttonList.filter(item => item.buttonLink !== "don't include")
}

这是我的junit测试文件"buildButtons.js">

import { buildButtonList } from "@/common/test.js"
let viewButtonList = [
{ buttonLabel: "ABOUT", buttonLink: "about" },
{ buttonLabel: "CONTACT", buttonLink: "contact" },
{ buttonLabel: "PRODUCTS", buttonLink: "prodcucts" },
{ buttonLabel: "DON'T INCLUDE", buttonLink: "don't include" }
]
let mockButtonList = [
{ buttonLabel: "ABOUT", buttonLink: "about" },
{ buttonLabel: "CONTACT", buttonLink: "contact" },
{ buttonLabel: "PRODUCTS", buttonLink: "prodcucts" }
]
let buttonList = []
let buildButtons = true
describe("Test buildButtonList function", () => {
it("Should call the function 'buildButtonList'", () => {
expect(buildButtonList()).toEqual(mockButtonList)
})
})

这是我测试的代码覆盖率的输出。

buildButtons的测试覆盖率结果

有人建议在单元测试用例中测试此代码时获得100%的代码覆盖率。我已经尝试过了,但是无法覆盖if条件在for循环中的行。

我不太清楚你所说的"分支机构覆盖率"是什么意思。,但是您可以设置应该测试的分支、函数和代码行的百分比。

// .jestrc.json
"coverageThreshold": {
"global": {
"branches": 80,
"functions": 80,
"lines": 40,
"statements": -20
}
},

以上将迫使您覆盖80%的分支,80%的函数和40%的行。如果你正在使用循环,那么我建议把它放在一个函数中,这样jest就可以获取函数本身的覆盖率。

旁注,我发现在大多数项目中将其设置为100%不是一个好主意,因为即快速路由器功能和套接字。IO服务器初始化并不能像jest期望的那样进行测试,因此您将有一些"未覆盖"的内容。根据笑话进行测试,即使你已经测试过了。100%只会让你失望。

最新更新