javascript - 如何从单元测试 JEST 中删除重复项?
问题描述
昨天,我用 Jest写了一个单元测试,今天我发现我做了一些重复的代码来做同样的测试。
我有一个文件:null.spec.js
包含这些测试:
import ArrayNull from "../../../../../src/1.x.x/scripts/array/has/null";
describe("Array has any null value", () => {
.......
it("should throw error if the parameter is not an array", () => {
function passNumber() {
ArrayNull.hasAnyNull(0);
}
function passString() {
ArrayNull.hasAnyNull("item");
}
expect(passNumber).toThrowError("The parameter should be an array");
expect(passString).toThrowError("The parameter should be an array");
});
it("should throw error if the parameter is undefined or null", () => {
function passUndefinedOrNull() {
ArrayNull.hasAnyNull(undefined || null);
}
expect(passUndefinedOrNull).toThrowError("The parameter is null or undefined");
});
it("should throw error if the array is empty", () => {
function pasEmptyArray() {
ArrayNull.hasAnyNull([]);
}
expect(pasEmptyArray).toThrowError("The array is empty");
});
});
describe("Array has at least a null value", () => {
...........
it("should throw error if the parameter is not an array", () => {
function passNumber() {
ArrayNull.hasAtLeastNull(0);
}
function passString() {
ArrayNull.hasAtLeastNull("item");
}
expect(passNumber).toThrowError("The parameter should be an array");
expect(passString).toThrowError("The parameter should be an array");
});
it("should throw error if the array is empty", () => {
function pasEmptyArray() {
ArrayNull.hasAtLeastNull([]);
}
expect(pasEmptyArray).toThrowError("The array is empty");
});
it("should throw error when the parameter is undefined or null", () => {
function passUndefinedOrNull() {
ArrayNull.hasAtLeastNull(undefined || null);
}
expect(passUndefinedOrNull).toThrowError("The parameter is null or undefined");
});
});
看看我it("should throw an error if the parameter is not an array", callback
在每个测试中是如何冗余编写的),即使它做同样的事情:抛出错误但具有不同的功能
第一个功能是:
hasAnyNull()
第二个功能是:
hasAtLeastNull()
如何删除和之间describe("Array has any null value", callback)
的这种重复
describe("Array has at least a null value", callback
)`?
解决方案
通过迭代值可以生成多个测试块:
[
['has any null', hasAnyNull],
['has at least a null', hasAtLeastNull]
].forEach(([description, fn]) => {
describe(`Array ${description} value`, () => {
it(...);
});
});
这可以就地完成或提取到辅助函数中。
当涉及到重复的describe
块时,这正是describe.each
它所做的,增加了描述格式:
describe.each([
['has any null', hasAnyNull],
['has at least a null', hasAtLeastNull]
])('Array %s value', (_description, fn) => {
it(...);
});
重复数据删除本身并不是目的。如果 DRY 代码变得比 WET 代码可读性差且容易出错,这可能是应用程序代码中的问题,但肯定是测试中的问题。如果应用程序代码由于复杂性而未能达到预期,则预计会在测试中检测到;这不适用于测试本身。
推荐阅读
- php - 如果没有正确显示结果
- typescript - typeorm:保存具有多对多关系ID的实体
- python - 如何交换python列表中项目的位置?
- java - 当@async 注释函数中出现多个请求时会发生什么?
- typescript - Typescript 从实现中推断通用类型
- reactjs - 使用 redux-form 创建自定义样式的 Material UI
- mysql - mysql:即使表没有改变,同样的选择也很慢
- linux - Yocto Bitbake Glibc 构建失败
- selenium - 如何为参数化变量编写xpath
- android - 滑动后 Cloud Firestore 不会在 Fragments 上显示数据