为什么不开玩笑地期望函数在 toMatchObject 中可用?

Why aren't jest expect functions available inside toMatchObject?

例如:

duty.forEach((dutyItem) => {
        expect(dutyItem).toMatchObject({
            person_id: expect.any(Number),
            date: expect.any(String),
            uxdate: expect.any(Number),
            is_split: expect.any(Number),
            split_rest_hours: expect.any(Number),
            aircraft_type_id: expect.toMatch(new RegExp('[0-9]|null')),
            type: expect.any(String),
            status: expect.any(String),
            location_start: expect.any(String),
            start: expect.any(String),
            uxstart: expect.any(Number),
            location_end: expect.any(String),
            end: expect.any(String),
            uxend: expect.any(Number),
            duty_time: expect.any(Number),
            is_zulu: expect.any(Number),
            is_flight: expect.any(Number),
        });
    });

returns:

TypeError: expect.toMatch 不是函数

明确匹配 属性 如:

aircraft_type_id: expect(dutyItem.aircraft_type_id).toMatch(..) 也不起作用。

查看 expect 方法 here。请注意,没有 expect.toMatch().toMatch() 是一个匹配函数,可用于 expect(value) 的 return 值,如 expect('abc').toMatch('abc').

看起来您想要做的是对每个 dutyItemaircraft_type_id 匹配特定的正则表达式。但是您正在尝试将匹配器用作对象中的值,这不太正确。相反,您可以使用 expect.any(Number)(如果它可以是字符串,则使用 String)并有第二个更明确的 expect 语句,如下所示:

duty.forEach((dutyItem)w => {
  const airVal = dutyItem.aircraft_type_id === null ? null : expect.any(Number);
  expect(dutyItem).toMatchObject({
    person_id: expect.any(Number),
    date: expect.any(String),
    uxdate: expect.any(Number),
    is_split: expect.any(Number),
    split_rest_hours: expect.any(Number),
    aircraft_type_id: airVal,
    type: expect.any(String),
    status: expect.any(String),
    location_start: expect.any(String),
    start: expect.any(String),
    uxstart: expect.any(Number),
    location_end: expect.any(String),
    end: expect.any(String),
    uxend: expect.any(Number),
    duty_time: expect.any(Number),
    is_zulu: expect.any(Number),
    is_flight: expect.any(Number),
  });
});

这允许第一个匹配项检查整个 dutyItem 对象的结构,然后对之后的 aircraft_type_id 进行更明确的测试。

有关您尝试的方法为何不起作用的更多详细信息...考虑您要 .toMatchObject 进行比较的对象。如果您的代码如下所示:

const matchObj = {
  key: expect.any(String)
};
expect(obj).toMatchObject(matchObj);

这意味着您希望 obj.key 匹配任何字符串。但是 matchObj.key 的值是多少?它不是一个函数,它是一个特殊的对象,Jest 知道它意味着“任何字符串”,当它比较 obj.key 的实际值时,它知道只检查它与任何字符串。

如果你有这个(如果它有效)那么 matchObj.key 会是什么?它将是 .toMatch() 的 return 值,这可能是 undefined,但在任何情况下都不是在 .toMatchObject() 函数期间有用的值。

const matchObj = {
  key: expect.toMatch(regex)   // key will be the return value of .toMatch
};
expect(obj).toMatchObject(matchObj);