Search code examples
node.jsunit-testingnpmtest-coveragenyc

How to meet the test coverage in the following Unit testing in Nodejs?


I am doing Unit testing in NodeJS. I have managed to see the coverage of my unit testing using NYC. I would like to know how can i widen my unit testing scope to increase the coverage of Statement branch and condition branch. I have the following code for testing.

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");
  });
});

Solution

  • If you pass def and abc as arguments, you can create a test for each case:

    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");
      });
    });