Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
118
rated 0 times [  124] [ 6]  / answers: 1 / hits: 74301  / 9 Years ago, mon, july 20, 2015, 12:00:00

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?


More From » jasmine

 Answers
8

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();
})
});
});

[#65740] Friday, July 17, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
isham

Total Points: 69
Total Questions: 86
Total Answers: 86

Location: Anguilla
Member since Sun, Jan 29, 2023
1 Year ago
;