javascript 是否有茉莉花匹配器来比较对象属性的子集
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15322793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a jasmine matcher to compare objects on subsets of their properties
提问by iwein
I have an object that may be extended along my behavior under test, but I want to make sure that the original properties are still there.
我有一个对象可以沿着我的测试行为扩展,但我想确保原始属性仍然存在。
var example = {'foo':'bar', 'bar':'baz'}
var result = extendingPipeline(example)
// {'foo':'bar', 'bar':'baz', 'extension': Function}
expect(result).toEqual(example) //fails miserably
I'd like to have a matcher that would pass in this case, along the lines of:
我希望有一个匹配器可以在这种情况下通过,如下所示:
expect(result).toInclude(example)
I know that I can write a custom matcher, but it seems to me that this is such a common problem that a solution should be out there already. Where should I look for it?
我知道我可以编写自定义匹配器,但在我看来,这是一个很常见的问题,应该已经有解决方案了。我应该在哪里寻找它?
回答by Kamil Szot
Jasmine 2.0
茉莉花 2.0
expect(result).toEqual(jasmine.objectContaining(example))
Since this fix: https://github.com/pivotal/jasmine/commit/47884032ad255e8e15144dcd3545c3267795dee0it even works on nested objects, you just need to wrap each object you want to match partially in jasmine.objectContaining()
由于此修复程序:https: //github.com/pivotal/jasmine/commit/47884032ad255e8e15144dcd3545c3267795dee0它甚至适用于嵌套对象,您只需要包装要部分匹配的每个对象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})
}));
});
回答by Chicna
I've had the same problem. I just tried this code, it works for me :
我遇到了同样的问题。我刚试过这段代码,它对我有用:
expect(Object.keys(myObject)).toContain('myKey');
回答by Brandon S?ren Culley
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.
我想我会提供一种使用现代 javascript map 和 rest 运算符的替代方法。我们可以使用带有 rest 运算符的解构来省略属性。请参阅本文中的进一步说明。
var example = {'foo':'bar', 'bar':'baz'}
var { extension, ...rest } = extendingPipeline(example)
expect(rest).toEqual(example)
回答by Wouter J
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;
}
});
});