是 - 测试 returns "serializes to the same string"

Jest - test returns "serializes to the same string"

我有这个测试:

describe('reminderEventLoopDateAfter', () => {
    test('returns start of the day, of a date 1 month in the future', () => {
        const testDate = date.reminderEventLoopDateAfter('2022-01-01T20:00:00+0500', 1, 'months');
        expect(testDate).toEqual('2022-02-01T00:00:00.000Z');
    });
});

其中 reminderEventLoopDateAfter 是:

const reminderEventLoopDateAfter = (now, days = 0, unit = 'day') => dayjs(now).utc().add(days, unit).startOf('day');

为什么我会被测试抛出这个?

Expected: "2022-02-01T00:00:00.000Z"
Received: serializes to the same string

Jest 告诉您打印到控制台时的 testDate2022-02-01T00:00:00.000Z。如果 Jest 打印出来(序列化 testDate

Expected: "2022-02-01T00:00:00.000Z"
Received: "2022-02-01T00:00:00.000Z"

作为测试结果,这会让人感到困惑,因为测试失败是因为实际的 testDate 是一个 Day.js 对象,它不等于字符串 "2022-02-01T00: 00:00.000Z”。您可能打算在对它们进行断言之前将“2022-02-01T00:00:00.000Z”转换为 Day.js 对象或将您的 testDate 转换为字符串。

testDate 对象不是字符串,而是对象。它恰好解析为字符串,但它们不相等,因此使用 toEqual 无法进行相同比较。您可以将测试更改为此,它应该可以工作:

expect(testDate.format()).toEqual('2022-02-01T00:00:00.000Z');

因为 format() 函数 returns 一个字符串,它允许你想要的比较。