Julio Rodriguez
Julio Rodriguez

Reputation: 515

How to pass an empty array in a unit test with Jasmine?

I'm working on an Angular project and I am testing a function that populates a variable name 'recentSearches' that renders an table using *ngFor on it, this function receives as a parameter a variable also named 'recentSearches' that is an array. I need to show a label above the table called "recents" when added the parameter 'recentSearches' is not empty.

I created a boolean property at the beggining of the class named 'recentSearchesHasValue', defaulted to false, and when the function is ran, if 'recentSearches' has elements I set 'recentSearchesHasValue' to true, then in the HTML I check, using *ngIf wheter 'recentSearchesHasValue' is true or false to show the 'recent' label. Everything works fine.

My problem is with the unit tests. I'm trying to create unit test for both cases when 'recentSearches' is an poulated object array and when it is empty. The first test I wrote pass, but the second doesn't pass the test. This is the function in the .ts that I described above:

handleRecentSearchesDisplay(recentSearches: RecentSearch[]): void {
    if (recentSearches) {
        this.recentSearchesHasValue = true;
        this.recentSearches = recentSearches;
        this.viewRecentSearches = [];
        for (const search of recentSearches) {
            this.viewRecentSearches.push(this.createRecentSearch(search));
        }

        if (!this.viewRecentSearches.length) {
            this.progressbarVisibility.emit(false);
        }
    }
}

And this are my tests that are failing:

describe('handleRecentSearchesDisplay', () => {
    let recentSearch: RecentSearch[] = RecentSearchesTestModal;

    it('display recent label if recentSearch is not empty', () => {
        spyOn(component, 'createRecentSearch');
        component.handleRecentSearchesDisplay(recentSearch);
        expect(component.recentSearchesHasValue).toBeTrue();
    });

    it('Do not display recent label if recentSearch is empty', () => {
        spyOn(component, 'createRecentSearch');
        let recentSearch = [];
        component.handleRecentSearchesDisplay(recentSearch);
        expect(component.recentSearchesHasValue).toBeFalse();
    });
});

How can I fix this?

Upvotes: 0

Views: 1584

Answers (1)

OLO
OLO

Reputation: 471

I think that you must change your if condition to:

handleRecentSearchesDisplay(recentSearches: RecentSearch[]): void {
    if (recentSearches?.length > 0) { // here you need to test if list is not empty
        this.recentSearchesHasValue = true;
        this.recentSearches = recentSearches;
        this.viewRecentSearches = [];
        for (const search of recentSearches) {
            this.viewRecentSearches.push(this.createRecentSearch(search));
        }

        if (!this.viewRecentSearches.length) {
            this.progressbarVisibility.emit(false);
        }
    }
}

Upvotes: 1

Related Questions