首页 > 解决方案 > 如何从单元测试 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在每个测试中是如何冗余编写的),即使它做同样的事情:抛出错误但具有不同的功能

如何删除和之间describe("Array has any null value", callback)的这种重复

describe("Array has at least a null value", callback)`?

标签: javascriptjestjs

解决方案


通过迭代值可以生成多个测试块:

[
  ['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 代码可读性差且容易出错,这可能是应用程序代码中的问题,但肯定是测试中的问题。如果应用程序代码由于复杂性而未能达到预期,则预计会在测试中检测到;这不适用于测试本身。


推荐阅读