【问题标题】:Jasmine expect toEqual but ignore additional properties on the actual object to prevent 'Expected ... not to have properties ...'Jasmine 期望 toEqual 但忽略实际对象上的其他属性以防止“期望......没有属性......”
【发布时间】:2019-10-30 12:58:19
【问题描述】:

有时我只需要声明实际对象的特定属性,而不关心其他属性。

例如:

const actual = [
  { a: 1, additionalProp: 'not interestig' },
  { a: 2, additionalProp: 'not interestig' }
];

expect(actual).toEqual([
  { a: 1 },
  { a: 2 }
])

目前失败:

预计 $[0] 没有属性
additionalProp: '随机值'

我该如何写期望?

我目前正在做这样的事情:

expect(actual.map(i => ({a: 1}))).toEqual([
  { a: 1 },
  { a: 2 }
])

但我不太喜欢它,它不适用于更复杂的对象

【问题讨论】:

    标签: javascript jasmine


    【解决方案1】:

    您可以显式处理特定对象及其相关属性吗?

    expect(actual.length).toBe(2);
    expect(actual[0]['a']).toBe(1);
    expect(actual[1]['a']).toBe(2);
    

    另一种方法是使用jasmine.obectContaining。如果预期的对象包含多个属性,这可能更合适。

    const expected = [
        { a: 1 },
        { a: 2 }
    ];
    expect(actual.length).toBe(expected.length);
    for (let i = 0; i < expected.length; i++) {
        expect(actual[i]).toEqual(jasmine.objectContaining(expected[i]));
    }
    

    【讨论】:

    • jasmine.objectContaining 足够接近
    猜你喜欢
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多