是否有茉莉花配对器来比较对象的属性子集

我有一个对象,它可以在测试中沿着我的行为进行扩展,但是我希望确保原始属性仍然存在。

var example = {'foo':'bar', 'bar':'baz'}


var result = extendingPipeline(example)
// {'foo':'bar', 'bar':'baz', 'extension': Function}


expect(result).toEqual(example) //fails miserably

我希望在这种情况下,有一个匹配器可以通过,大致如下:

expect(result).toInclude(example)

我知道我可以编写一个自定义匹配器,但是在我看来,这是一个非常常见的问题,应该已经有一个解决方案了。我应该去哪里找?

51548 次浏览

I don't think it is that common and I don't think you can find one. Just write one:

beforeEach(function () {
this.addMatchers({
toInclude: function (expected) {
var failed;


for (var i in expected) {
if (expected.hasOwnProperty(i) && !this.actual.hasOwnProperty(i)) {
failed = [i, expected[i]];
break;
}
}


if (undefined !== failed) {
this.message = function() {
return 'Failed asserting that array includes element "'
+ failed[0] + ' => ' + failed[1] + '"';
};
return false;
}


return true;
}
});
});

Jasmine 2.0

expect(result).toEqual(jasmine.objectContaining(example))

Since this fix: https://github.com/pivotal/jasmine/commit/47884032ad255e8e15144dcd3545c3267795dee0 it even works on nested objects, you just need to wrap each object you want to match partially in jasmine.objectContaining()

Simple example:

it('can match nested partial objects', function ()
{
var joc = jasmine.objectContaining;
expect({
a: {x: 1, y: 2},
b: 'hi'
}).toEqual(joc({
a: joc({ x: 1})
}));
});

I've had the same problem. I just tried this code, it works for me :

expect(Object.keys(myObject)).toContain('myKey');

I thought that I would offer an alternative using modern javascript map and rest operator. We are able to omit properties using destructuring with rest operator. See further description in this article.

var example = {'foo':'bar', 'bar':'baz'}


var { extension, ...rest } = extendingPipeline(example)


expect(rest).toEqual(example)

jasmine.objectContaining() only works for a single layer.

expect(result).toMatchObject(example) checks that the object example that is passed in matches a subset of the properties of result.