Max*_*sey 5 javascript testing jestjs
我想测试数组是否为空或包含特定结构的对象。在伪代码中,它可能是这样的:
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
Run Code Online (Sandbox Code Playgroud)
也许我对 Jest 中的工作方式的理解是错误的,但对我来说,我的问题看起来像是一个或问题。
在测试套件中封装逻辑或的最佳方法是排除测试本身内部的特定情况。例如:
it('has an array of objects', () => {
if (arr.length > 0) {
expect(arr).toBe(expect.arrayContaining(expect.toMatchObject({ foo: expect.any(String) })));
}
});
Run Code Online (Sandbox Code Playgroud)
但是,我认为更适合单元测试的方法是分离您的关注点。一项测试何时存在空数组,一项测试何时属性foo设置为'bar',等等。
| 归档时间: |
|
| 查看次数: |
12836 次 |
| 最近记录: |