4

I am trying to write a test to ensure that my method returns the right value based on one of the component's properties. So in my unit test I want to set the value of the component's properties and then call the component's method that is supposed return a boolean based on that value, however it is not working as intended.

The component's method is very simple:

isLoading(): boolean {
    return this.matches === [];
}

and here is my current unit test:

it('should have isLoading reflect whether there are matches', () => {
    expect(component.matches).toBeDefined();

    component.matches = [];
    console.log(component.isLoading());
    expect(component.isLoading()).toEqual(true);

    component.matches = [{name: 'object'}];
    console.log(component.isLoading());
    expect(component.isLoading()).toEqual(false);
});

Both console.logs output false and I'm not sure why.

Chris Lang
  • 384
  • 2
  • 19
  • A plunkr always helps :) – Guntram Sep 06 '17 at 22:19
  • Please consider rephrasing this question for posterity. These are not attributes they are properties. Well it may sound pedantic, in practice the distinction is very significant in the context of the angular templating language. – Aluan Haddad Oct 20 '17 at 03:07

2 Answers2

0

If matches is not defined or null, it is not of type array. So you maybe compare:

if (this.matches is an array and empty)...
// but if it is not initialized (undefined) or initialized as null...

Try:

isLoading(): boolean {
    return !this.matches || (this.matches && this.matches === []);
    // i would leave the () brackets to make it easier to read
}

or e.g.:

isLoading(): boolean {
    return !this.matches || !this.matches.length;
}

Look at the position where you declare this.matches. E.g. in the constructor:

constructor(
    public matches: any[] = null
) {}

or:

export class MyComponent {
    public matches: any[] // <- undefined, not initialized
Guntram
  • 961
  • 14
  • 19
0

I made the mistake of assuming [] == []

In javascript, comparing objects (which includes arrays) with == or === checks that they are the same object and in this case they are not.

Why isn't [1,2,3] equal to itself in Javascript?

Chris Lang
  • 384
  • 2
  • 19