Not able to change a component's property from unit test

1.7k Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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?

1
On

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