Home > Net >  Angular test branches inside method
Angular test branches inside method

Time:12-24

I have this method in my TS file,

It has 3 branches inside it.

In angular with jasmine, how can i test all this branches?

getAges(ages: Ages) {
    if (ages) {
      return ages.number ? 10 : 20;
    }
    return 30;
  }

CodePudding user response:

This way you can all three paths:

class TestClass {

  getAges(ages: any) {
    if (ages) {
      return ages.number ? 10 : 20;
    }
    return 30;
  }
}

describe('getAges', () => {
  const subject: TestClass = new TestClass();

  it('when no ages are provided', () => {
    expect(subject.getAges(null)).toBe(30);
  });

  it('ages has a value', () => {
    const ages = { number: 5 };
    expect(subject.getAges(ages)).toBe(10);
  });

  it('ages does not have a value', () => {
    const ages = {};
    expect(subject.getAges(ages)).toBe(20);
  });
});

TestClass is just used as an example here.

  • Related