简体   繁体   中英

jest test cases for typescript function with no return

I have component in reactjs-

export const initializeValues=()=>{
  if(window.variable1$==undefined || window.variable1$==null)
  {
    window.variable1$=const.variable1Value;
  }

  if(window.variable2$==undefined || window.variable2$==null)
  {
    window.variable2$=const.variable2Value;
  }
}

I have written test case in jest for this as -

describe("initializeValues",()=>{

    test("Variable1",()=>{
      expect(window.variable1$).toBeUndefined();
     });

    test("Variable2",()=>{
      expect(window.variable2$).toBeUndefined();
     });
});

The test cases written above runs successfully. But it shows only 5% of code coverage.

How can I add more test cases when function is not returning anything? (with just assignment of values)

I am not quite sure what const.variable1Value is but anyway. In the test you should prepare the test preconditions and run the tested function. You can check in coverage report what actually is covered. There are information about eg else path not taken and you must also cover that.

In this case following tests are needed:

  • for the first condition:
// covers first part of first if statement
it("should set variable1 if undefined", () => {
  window.variable1 = undefined;
  initializeValues();
  expect(window.variable1).toEqual(variable1Value)
});

// covers second part of first if statement
it("should set variable1 if null", () => {
  window.variable1 = null;
  initializeValues();
  expect(window.variable1).toEqual(variable1Value)
});

// covers else part of first if statement
it("should not set variable1 if already set", () => {
    window.variable1 = "some value different than variable1Value";
    initializeValues();
    expect(window.variable1).toEqual("some value different than variable1Value")
});

Same set for the second if statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM