【问题标题】:How to meet the test coverage in the following Unit testing in Nodejs?如何满足以下 Nodejs 单元测试中的测试覆盖率?
【发布时间】:2021-08-17 06:03:22
【问题描述】:

我正在 NodeJS 中进行单元测试。我已经设法看到使用 NYC 进行单元测试的覆盖率。我想知道如何扩大我的单元测试范围以增加语句分支和条件分支的覆盖范围。我有以下代码用于测试。

const value = () => {
  const def = "defvalue";
  const abc = "abcvalue";

  if(abc && abc !== "undefined"){
    return abc
  }else if (def && def !== "undefined"){
    return def
  }else{
    return false
  }
}

//Function to do unit testing.
describe("the result function", () => {    
  it("should return false", () => {
    const result = value();
    console.log("The result is:", result);
    expect(result).to.be.false;
  });
  
  it("should return abc", () => {
    const result = value();
    console.log("The result is:", result);
    expect(result).to.be.eq("abc");
  });
  
  it("should return def", () => {
    const result = value();
    console.log("The result is:", result);
    expect(result).to.be.eq("def");
  });
});

【问题讨论】:

  • 您总是以完全相同的方式调用该函数。您如何期望每次都有不同的结果?
  • @TobiasS。 .. 感谢你的回复。有什么办法,我可以同时从 if、else if 和 else 条件中测试我的代码。如果有任何想法,请在这里帮助我:)

标签: node.js unit-testing npm test-coverage nyc


【解决方案1】:

如果将 def 和 abc 作为参数传递,则可以为每个案例创建一个测试:

const value = (def, abc) => {

  if(abc && abc !== "undefined"){
    return abc
  }else if (def && def !== "undefined"){
    return def
  }else{
    return false
  }
}

//Function to do unit testing.
describe("the result function", () => {    
  it("should return false", () => {
    const result = value();
    console.log("The result is:", result);
    expect(result).to.be.false;
  });
  
  it("should return abc", () => {
    const result = value("abc", undefined);
    console.log("The result is:", result);
    expect(result).to.be.eq("abc");
  });
  
  it("should return def", () => {
    const result = value(undefined, "def");
    console.log("The result is:", result);
    expect(result).to.be.eq("def");
  });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-18
    • 1970-01-01
    • 2014-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多