Javascript 测试数组是否为空或是否包含具有
我想测试数组是空的还是包含特定结构的对象。在伪代码中,可能是这样的:Javascript 测试数组是否为空或是否包含具有,javascript,testing,jestjs,Javascript,Testing,Jestjs,我想测试数组是空的还是包含特定结构的对象。在伪代码中,可能是这样的: expect([]) .toHaveLength(0) .or .arrayContaining( expect.toMatchObject( { foo: expect.any(String) } ) ) => true expect([{foo: 'bar'}]) .toHaveLength(0) .or .arrayContaining( expect
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
也许我在事情如何运作的问题上弄错了,但对我来说,我的问题看起来像一个or问题。在测试套件中封装逻辑or的最好方法是只在测试本身中排除特定的情况。例如:
it('has an array of objects', () => {
if (arr.length > 0) {
expect(arr).toBe(expect.arrayContaining(expect.toMatchObject({ foo: expect.any(String) })));
}
});
然而,我认为一种更为单元测试友好的方法是分离您的关注点。一个测试是关于何时存在空数组,一个测试是关于何时将
foo
属性设置为'bar'
,等等。谢谢,我还发现这篇文章,结合您所写的内容,非常有帮助。是的,如果您发现自己更经常地测试这种情况,我认为定制匹配器将是一个很好的解决方案。不过,我想知道您是否正在编写一个测试用例,而您应该编写两个