String array comparison using Jasmine toContains or toMatch

Viewed 856

I have a string array names which gets dynamically filled with the names from a dataset. Three names in this array are always the same even though the dataset is changed. So, in my spec I want to check if the names array contains these three specific names. But the matchers aren't helping me in Jasmine.

Example:

names = ["a", "b", "c", "d", "e", "f", "g"];
expect(names).toContain("b","d","c"); // this should return true as b, d, and c are in the names array

The above expect statement doesn't work. Is there a way to use toMatch and use a regex to solve this problem?

Could anyone help me out with this.

Thank you.

2 Answers

Instead of using toContain() you can simply implement the following function and expect the result to be true or false.

function arrayContains(superset, subset) {
    if (subset.length === 0) return false;
    return subset.every(function (value) {
        return (superset.indexOf(value) >= 0);
    });
}

Now, you can call this function inside your expect statement as follows:

expect(arrayContains(names,["b", "d", "c"])).toBe(true);

As you have mentioned, the three names are always expected, you can assign it to a variable and just pass that in the function above.

Hope that helps. You can even implement a customMatcher if necessary.

.toContain method takes only one argument, that is your mistake

So you can call three .toContain

Or try something like expect(_.difference(["b","d","c"], names).length).toBe(0, 'names "b","d","c" are not contained in ' + names)

read more about difference method https://lodash.com/docs/4.17.4#difference

Related