sfletche sfletche - 1 month ago 9
Javascript Question

Jasmine test for object properties

What I'd like to do

describe('my object', function() {
it('has these properties', function() {
expect(Object.keys(myObject)).toEqual([
'property1',
'property2',
...
]);
});
});


but of course
Object.keys
returns an array, which by definition is ordered...I'd prefer to have this test pass regardless of property ordering (which makes sense to me since there is no spec for object key ordering anyway...(at least up to ES5)).

How can I verify my object has all the properties it is supposed to have, while also making sure it isn't missing any properties, without having to worry about listing those properties in the right order?

Answer

You could use _.has (which wraps myObject.hasOwnProperty(prop)):

var _ = require('underscore');
describe('my object', function() {
  it('has these properties', function() {
    var props = [
      'property1',
      'property2',
      ...
    ];
    props.forEach(function(prop){
      expect(_.has(myObject, prop)).toBeTruthy();
    })
  });
});

edit I forgot its built in now!

describe("jasmine.objectContaining", function() {
  var foo;

  beforeEach(function() {
    foo = {
      a: 1,
      b: 2,
      bar: "baz"
    };
  });

  it("matches objects with the expect key/value pairs", function() {
    expect(foo).toEqual(jasmine.objectContaining({
      bar: "baz"
    }));
    expect(foo).not.toEqual(jasmine.objectContaining({
      c: 37
    }));
  });
});