如何写好前端单元测试

随着前端实现的业务逻辑愈发复杂,前端单元测试的重要性也水涨船高。 而好的单元测试,不仅能够保证代码质量,还能够提高开发效率。 本文就来谈谈,如何写好前端单元测试。 背景 简单介绍下背景,笔者在工作中负责开发前端 SDK,测试框架使用 jest。 我们项目对代码测试覆盖率有一定的要求,需要满足: { "branches": 80, "functions": 80, "lines": 80, "statements": 80 } 比如我们需要测试这个函数: export const getConfig = (name) => { return { foo: () => {}, name: name || "Anonymous", }; }; 对应的测试用例一般是这样的: describe("getConfig", () => { test("should return name if have the paramter", () => { const name = "zxf4399"; const config = getConfig(name); expect(config.name).toBe(name); }); test("should return default name if doesn't have the paramter", () => { const config = getConfig(); expect(config....

十二月 21, 2022 · 4 分钟 · 761 字