【问题标题】:Jest to match every object in array开玩笑匹配数组中的每个对象
【发布时间】:2021-11-04 03:38:23
【问题描述】:

我想检查数组中的每个对象是否都包含一个属性“a”,其值为数字。


  test('a must be number always', () => {
        let response = [{ a: 'asdasd', y: 2 }, { a: 12 }];
        expect(response).toEqual(
            expect.arrayContaining([
                expect.objectContaining({ a: expect.any(Number) })
            ])
        );
    });

上述情况正在通过,因为 jest 能够找到至少 1 个包含带有数字的属性“a”的对象。但我希望每个对象都有编号。类似于Array.every

在上面的继续中,我们如何将对象属性匹配为数字或字符串。

  test('a must be either number or String always', () => {
        let response = [{ a: 'asdasd', y: 2 }, { a: true }];
        expect(response).toEqual(
            expect.arrayContaining([
                expect.objectContaining({ a: expect.any(Number) or expect.any(String) or `expect a = 4` })
            ])
        );
    });

【问题讨论】:

    标签: jestjs


    【解决方案1】:

    我刚开始使用 Jest,老实说,我对它的方法名称及其误导性语义感到非常失望……我想念 @hapi/code 或 柴。

    也就是说,您可以按如下方式实现您的测试,但如果有人提出更好的方法,我会很高兴:

    test('a must be number always', () => {
      let response = [{ a: 'asdasd', y: 2 }, { a: 12 }];
      response.forEach(el => {
        // check each element of the array, individually
        expect(el).toEqual(expect.objectContaining({ a: expect.any(Number) }))
      })
    });
    
    // Message shows no reference to the array
    // expect(received).toEqual(expected) // deep equality
    // Expected: ObjectContaining {"a": Any<Number>}
    // Received: {"a": "asdasd", "y": 2}
    

    另一种更接近原始代码的方法可能如下:

    test.only('a must be number always', () => {
      let response = [{ a: 'q', y: 2 }, { a: 12 }];
    
      expect(response).toEqual(
        // the array must NOT contain an element that does NOT contain {a: _number_}
        expect.not.arrayContaining([
          expect.not.objectContaining({a: expect.any(Number)})
        ])
      );
    });
    
    
    // Message references the array, but in a cryptic way:
    // expect(received).toEqual(expected) // deep equality
    // Expected: ArrayNotContaining [ObjectNotContaining {"a": Any<Number>}]
    // Received: [{"a": "q", "y": 2}, {"a": 12}]
    

    【讨论】:

      猜你喜欢
      • 2018-10-15
      • 2019-01-02
      • 2018-10-23
      • 2021-08-28
      • 2020-04-30
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      • 2019-07-08
      相关资源
      最近更新 更多