准备测试
安装 jest
pnpm add jest -D要测试的函数
const englishCode = "en-US";
const spanishCode = "es-ES";
function getAboutUsLink(language) {
switch (language.toLowerCase()) {
case englishCode.toLowerCase():
return "/about-us";
case spanishCode.toLowerCase():
return "/acerca-de";
}
return "";
}
module.exports = getAboutUsLink;测试示例,用 *.spec.js 或 *.test.js 后缀
const getAboutUsLink = require("./index");
test("Returns about-us for english language", () => {
expect(getAboutUsLink("en-US")).toBe("/about-us");
});运行测试
安装测试运行工具
pnpm add jest-cli -D配置 package.json 脚本
{
"scripts": {
"test": "jest"
}
}跑测试
pnpm test覆盖率
查看测试是否完善,追求 100%,但不一定要达到
配置脚本
{
"scripts": {
"test": "jest --coverage"
}
}运行之后会生成 coverage 文件夹,打开 coverage/locv-report/index.html 可以看到测试覆盖情况
拓展
安装拓展可以方便运行测试,每次保存文件都会重新运行一次测试
cmd + shift + p 搜索 toggle coverage 并选择会打开开关,在文件中高亮显示测试未覆盖到的代码行