0

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");
  });
});
Smile Kisan
  • 191
  • 4
  • 19
  • You are always calling the function exactly the same way. How are you expecting a different result each time? – Tobias S. Aug 17 '21 at 07:13
  • @TobiasS. .. Thank you for your reply. Is there any way, I can test my code from if, else if and else condition at once. If any idea please help me out here :) – Smile Kisan Aug 17 '21 at 07:21

1 Answers1

1

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");
  });
});
Tobias S.
  • 21,159
  • 4
  • 27
  • 45