0

Hey so I have this method in my Angular app which I want to unit test:

public methodEquip(someBonus: Parameters) {
    let flag = false;
    for (const shield of someBonus.items) {
        if (shield.added.length !== 0 || shield.removed.length !== 0) {
            flag = true
        }
        if (flag) {
            return true;
        } else {
            return false;
        }
    }
}

I want to unit test it with Jasmine. I can do simple unit tests but it's too much for me now, I'm stucked. I'm quite new to unit tests and I don't know how to do it :/ Can you help me?

I have only this for now, and I don't know how to do the rest of it:

it('tests methodEquip', () => {
       let flag = false;
       const newMocked = new Parameters;
       component.methodEquip(newMocked);        
});
uminder
  • 23,831
  • 5
  • 37
  • 72
blackko2
  • 3
  • 2

1 Answers1

0

With Jasmine, any matcher can evaluate to a negative assertion by chaining the call to expect with a not before calling the matcher.

For primitive types (boolean, number, string etc.):

expect(actual).not.toBe(x);

For objects:

expect(actual).not.toEqual(x);

In your case, the test could look as follows:

it('#methodEquip should not return false when ...', () => {
    const parameters = new Parameters;
    const actual = component.methodEquip(parameters);
    expect(actual).not.toBe(false);
});

Since boolean has only two possible values, it would however make more sense to simply write expect(actual).toBe(true);

uminder
  • 23,831
  • 5
  • 37
  • 72
  • Can I manipluate length value to check other options? Does it make sense or this single test should be enough? – blackko2 Dec 17 '19 at 18:01
  • You typically write 1-n unit tests per method to make sure all different code branches are executed at least ones and produce the expected results. – uminder Dec 18 '19 at 04:57
  • I got error "Cannot read property 'length' of undefined" with this test case, I'm looking for some tips right now – blackko2 Dec 27 '19 at 13:01