Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 809
sfletche Avatar asked Jul 20 '15 23:07

sfletche


People also ask

What is Jasmine testing used for?

It's used to test a specific behavior of the JavaScript code that's usually encapsulated by an object/class or a function. It's created using the Jasmine global function describe() that takes two parameters, the title of the test suite and a function that implements the actual code of the test suite.

How do you test Jasmine methods?

Jasmine is one of the popular JavaScript unit testing frameworks which is capable of testing synchronous and asynchronous JavaScript code. It is used in BDD (behavior-driven development) programming which focuses more on the business value than on the technical details.


2 Answers

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();     })   }); }); 
like image 140
Plato Avatar answered Sep 18 '22 19:09

Plato


The simplest solution? Sort.

var actual = Object.keys(myObject).sort(); var expected = [   'property1',   'property2',   ... ].sort();  expect(actual).toEqual(expected); 
like image 26
Jordan Running Avatar answered Sep 19 '22 19:09

Jordan Running