2

I have an array:

const dummyArr = [
    { name: "a", city: "c1" },
    { name: "b", city: "c2" },
    { name: "z", city: "c3" }
]

I need to write a jasmine test, to verify if an element exists in an array with property name: b.
Not sure if I can use arrayContaining or objectContaining here.

Note: I need to verify this within toHaveBeenCalledWith

expect(obj.setArray).toHaveBeenCalledWith("personalDetails", .......)
CodeBreaker
  • 95
  • 4
  • 12
  • 2
    Possible duplicate of [How to determine if Javascript array contains an object with an attribute that equals a given value?](https://stackoverflow.com/questions/8217419/how-to-determine-if-javascript-array-contains-an-object-with-an-attribute-that-e) – Martin Zeitler Mar 04 '19 at 23:58
  • 1
    `.toHaveBeenCalledWith()` does not seem to apply; I'd use `expect(dummyArr.find(function(ele) {return ele.name === 'b';})).toBe(true);`. – Martin Zeitler Mar 05 '19 at 00:10
  • `setArray` was spied upon `obj`. As I knew it was first time call to `setArray`, `dummyArr` was second param and index of object element I wanted from `dummyArr`. This got me working `const elem = obj.setArray.calls.argsFor(0)[1];` `expect(elem[0].name).toEqual("b");` – CodeBreaker Mar 06 '19 at 22:08
  • the down-side with index access is that a specific order of items is being expected, which might or might not be given - and so the test might fail, even if the input is perfectly valid. access by property-name tends to be rather solid. – Martin Zeitler Mar 06 '19 at 23:42

1 Answers1

0

Here's one other way to do it without a custom matcher. I am assuming dummyArr is your fake data, and you want to verify setArray gets called with the second element (named 'b').

expect(obj.setArray).toHaveBeenCalledWith(
  jasmine.arrayContaining([dummyArr.find(el => e.name === 'b')])
);

Depending on what you think it's readable, you could do the lookup before the expect:

const dummyEl = dummyArr.find(el => e.name === 'b');
expect(obj.setArray).toHaveBeenCalledWith(jasmine.arrayContaining([dummyEl]));

Note that this passes when setArray gets called with any array containing that element, e.g. the whole dummyArr. If you want an exact match, use jasmine.arrayWithExactContents() instead.

Dan C.
  • 3,643
  • 2
  • 21
  • 19