如何测试验证器功能

时间:2020-11-06 11:35:58

标签: javascript unit-testing jasmine

我有一个带有2个验证方法的类。第一个检查对象是否具有给定的属性,第二个检查对象是否具有“ contentDE”,“ contentENG”属性。看一下代码。

export class Validators {
  static hasNotEmptyPropertis(obj, properties) {
    let has = true;
    properties.forEach((property) => {
      has =
        has &&
        property in obj &&
        typeof obj[property] === "string" &&
        obj[property].trim().length > 0;
    });

    return has;
  }

  static hasContent(obj) {
    return this.hasNotEmptyPropertis(obj, ["contentDE", "contentENG"]);
  }
}

总而言之,hasContent方法使用更通用的hasNotEmptyPropertis方法。

在测试“ hasContent”方法时,应检查是否使用特定参数调用了“ hasNotEmptyPropertis”方法,或者它是否可以检查函数返回的值。 假设我有一个经过良好测试的“ hasNotEmptyProperties”方法,那么测试“ hasContent”返回的值对我来说似乎是多余的。另一方面,现在有太多关于不测试实现细节的讨论。看一下样本测试。

describe("What return function", () => {
  it("Should return false when validate object with empty 'contentPL' property", () => {
    expect(Validators.hasContent({ contentDE: "", contentENG: "ENG" }));
  });

  it("Should return false when validate object with empty 'contentENG' property", () => {
    expect(Validators.hasContent({ contentDE: "DE", contentENG: "" }));
  });

  // There will still be tests if the property contains only white space, if it is not a string, etc ...
});

describe("What do function", () => {
  it("Should call 'hasNotEmptyPropertis' method with contents properties", () => {
    const obj = { contentDE: "de", contentENG: " " };
    const properties = ["contentPL", "contentENG"];
    Validators.hasContent(obj);

    expect(Validators.hasNotEmptyPropertis).toHaveBeenCalledWith(
      obj,
      properties
    );
  });

  // In this case, our tests actually end.
});

现在假设我有更多功能,例如“ hasContent”。 “ hasAnswers”等 分别测试每个这样的函数并检查该属性可以是未定义的,null,空字符串,仅空格等...似乎是多余的,因为我确信“ hasNotEmptyPropertis”可以正常工作,我要做的就是检查它是否从预期参数调用。但是,我不知道它与不测试实现细节有何关系。 也有可能对“ hasNotEmptyPropertis”功能的测试将不正确,然后对“ hasContent”的自动测试将不正确。 还是有其他方法可以测试类似的东西?

0 个答案:

没有答案