Search code examples
unit-testingjasminekarma-jasmine

Jasmine | How to test if any object is an array


I am migrating my angular application from the Mocha, Sinon, and Chai framework to Jasmine. In Chai/Moch we do have something 'expect(result).to.be.an('array').that.include('XYZ');' How to check 'Array' in Jasmine? For the array content check, I know 'toContain' will work fine but couldn't find any solution for 'Array' check. I really appreciate any help you can provide.


Solution

  • In Jasmine, .toBe does a reference check and .toEqual does an equality check. Most times when asserting array or object types, you would want to use .toEqual.

    const a = [];
    const b = a;
    const c = [];
    expect(a).toBe(b); // passes
    expect(a).toBe(c); // fails
    expect(a).toEqual(c); // passes
    

    To check if something is an array, you can use the Array.isArray helper from JavaScript.

    const a = [1, 2];
    expect(Array.isArray(a)).toBeTrue(); // passes
    expect(a).toEqual([1, 2]); // passes