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

2022-01-11 00:00:00 unit-testing jasmine javascript

我有一个对象可以根据我的被测行为进行扩展,但我想确保原始属性仍然存在.

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?

推荐答案

Jasmine 2.0

Jasmine 2.0

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

自从这个修复:https://github.com/pivotal/jasmine/commit/47884032ad255e8e15144dcd3545c3267795de/一>它甚至适用于嵌套对象,您只需将要部分匹配的每个对象包装在 jasmine.objectContaining()

简单示例:

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

相关文章