我想编写一个断言给定对象不具有某些属性的测试。
假设我有一个函数
function removeFooAndBar(input) {
delete input.foo;
delete input.bar;
return input;
}
现在我要写一个测试:
describe('removeFooAndBar', () => {
it('removes properties `foo` and `bar`', () => {
const data = {
foo: 'Foo',
bar: 'Bar',
baz: 'Baz',
};
expect(removeFooAndBar(data))
.toEqual(expect.objectContaining({
baz: 'Baz', // what's left
foo: expect.not.exists() // pseudo
bar: undefined // this doesn't work, and not what I want
}));
});
});
断言的正确方法是什么?
最佳答案
在评论中讨论后更新
您可以使用 expect.not.objectContaining()
.这种方法工作正常,但有一个不幸的边缘情况:它在属性存在但 undefined
或 null
时匹配。要解决此问题,您可以明确添加要包含在检查中的那些值。你需要 jest-extended
toBeOneOf()
的包裹匹配器。
expect({foo: undefined}).toEqual(expect.not.objectContaining(
{foo: expect.toBeOneOf([expect.anything(), undefined, null])}
));
嵌套 Prop 失败的示例:
const reallyAnything = expect.toBeOneOf([expect.anything(), undefined, null]);
expect({foo: undefined, bar: {baz: undefined}}).toEqual(
expect.not.objectContaining(
{
foo: reallyAnything,
bar: {baz: reallyAnything},
}
)
);
原始答案
我要做的是显式检查对象是否具有名为 bar
或 foo
的属性。
delete data.foo;
delete data.bar;
delete data.nested.property;
expect(data).not.toHaveProperty('bar');
expect(data).not.toHaveProperty('foo');
expect(data.nested).not.toHaveProperty('property');
// or
expect(data).not.toHaveProperty('nested.property');
或者通过遍历将被删除的属性来减少重复。
const toBeRemoved = ['foo', 'bar'];
toBeRemoved.forEach((prop) => {
delete data[prop];
expect(data).not.toHaveProperty(prop);
});
但是,循环方法对于可能的嵌套对象来说并不是太好。
我相信你要找的是expect.not.objectContaining()
expect(data).toEqual(expect.not.objectContaining({foo: 'Foo', bar: 'Bar'}));
expect.not.objectContaining(object)
matches any received object that does not recursively match the expected properties. That is, the expected object is not a subset of the received object. Therefore, it matches a received object which contains properties that are not in the expected object. - Jest Documentation
关于javascript - Jest : expect object not to have property,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72219389/