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?
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.
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.
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(); }) }); });
The simplest solution? Sort.
var actual = Object.keys(myObject).sort(); var expected = [ 'property1', 'property2', ... ].sort(); expect(actual).toEqual(expected);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With