36
votes

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?

7

7 Answers

55
votes

It's 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
    }));
  });
});

Alternatively, you could use external checks like _.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();
    })
  });
});
13
votes

The simplest solution? Sort.

var actual = Object.keys(myObject).sort();
var expected = [
  'property1',
  'property2',
  ...
].sort();

expect(actual).toEqual(expected);
9
votes
it('should contain object keys', () => {
  expect(Object.keys(myObject)).toContain('property1');
  expect(Object.keys(myObject)).toContain('property2');
  expect(Object.keys(myObject)).toContain('...');
});
4
votes

I ended up here because I was looking for a way to check that an object had a particular subset of properties. I started with _.has or Object.hasOwnProperties but the output of Expected false to be truthy when it failed wasn't very useful.

Using underscore's intersection gave me a better expected/actual output

  var actualProps = Object.keys(myObj); // ["foo", "baz"]
  var expectedProps =["foo","bar"];
  expect(_.intersection(actualProps, expectedProps)).toEqual(expectedProps);

In which case a failure might look more like Expected [ 'foo' ] to equal [ 'foo', 'bar' ]

0
votes

Here are some new possible solutions too:

0
votes

I prefer use this; becouse, you have more possibilities to be execute indivual test.

import AuthRoutes from '@/router/auth/Auth.ts';

describe('AuthRoutes', () => {
    it('Verify that AuthRoutes be an object', () => {
        expect(AuthRoutes instanceof Object).toBe(true);
    });

    it("Verify that authroutes in key 'comecios' contains expected key", () => {
        expect(Object.keys(AuthRoutes.comercios)).toContain("path");
        expect(Object.keys(AuthRoutes.comercios)).toContain("component");
        expect(Object.keys(AuthRoutes.comercios)).toContain("children");
        expect(AuthRoutes.comercios.children instanceof Array).toBe(true);

        // Convert the children Array to Object for verify if this contains the spected key
        let childrenCommerce = Object.assign({}, AuthRoutes.comercios.children);
        expect(Object.keys(childrenCommerce[0])).toContain("path");
        expect(Object.keys(childrenCommerce[0])).toContain("name");
        expect(Object.keys(childrenCommerce[0])).toContain("component");
        expect(Object.keys(childrenCommerce[0])).toContain("meta");

        expect(childrenCommerce[0].meta instanceof Object).toBe(true);
        expect(Object.keys(childrenCommerce[0].meta)).toContain("Auth");
        expect(Object.keys(childrenCommerce[0].meta)).toContain("title");

    })
});
-1
votes

I am late to this topic but there is a a method that allows you to check if an object has a property or key/value pair:

expect(myObject).toHaveProperty(key);
expect({"a": 1, "b":2}).toHaveProperty("a");

or

expect(myObject).toHaveProperty(key,value);
expect({"a": 1, "b":2}).toHaveProperty("a", "1");