我想测试一个数组是否为空,或者是否包含某个结构的对象。在伪代码中,它可能是这样的:
expect([])
.toHaveLength(0)
.or
.arrayContaining(
expect.toMatchObject(
{ foo: expect.any(String) }
)
) => true
expect([{foo: 'bar'}])
.toHaveLength(0)
.or
.arrayContaining(
expect.toMatchObject(
{ foo: expect.any(String) }
)
) => true
expect([1])
.toHaveLength(0)
.or
.arrayContaining(
expect.toMatchObject(
{ foo: expect.any(String) }
)
) => false
也许我在Jest中是如何工作的问题上搞错了,但对我来说,我的问题看起来像是一个或-问题。
发布于 2018-08-30 08:42:36
在您的测试套件中封装逻辑或的最好方法是将特定的情况排除在测试本身之外。例如:
it('has an array of objects', () => {
if (arr.length > 0) {
expect(arr).toBe(expect.arrayContaining(expect.toMatchObject({ foo: expect.any(String) })));
}
});
但是,我认为一种更有利于单元测试的方法是将您的关注点分开。一个测试何时存在空数组,另一个测试何时将foo
属性设置为'bar'
,依此类推。
https://stackoverflow.com/questions/52080746
复制相似问题