Lie*_*ero 5 javascript jasmine
有时我只需要断言实际对象的特定属性,而不关心其他属性。
例如:
const actual = [
{ a: 1, additionalProp: 'not interestig' },
{ a: 2, additionalProp: 'not interestig' }
];
expect(actual).toEqual([
{ a: 1 },
{ a: 2 }
])
Run Code Online (Sandbox Code Playgroud)
目前失败的原因是:
预计 $[0] 不具有属性
additionalProp:'随机值'
怎样写出期望呢?
我目前正在做这样的事情:
expect(actual.map(i => ({a: 1}))).toEqual([
{ a: 1 },
{ a: 2 }
])
Run Code Online (Sandbox Code Playgroud)
但我不太喜欢它并且它不适用于更复杂的对象
您可以明确地解决特定对象及其相关属性吗?
expect(actual.length).toBe(2);
expect(actual[0]['a']).toBe(1);
expect(actual[1]['a']).toBe(2);
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用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]));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3482 次 |
| 最近记录: |