You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jest使用toHaveBeenCalledWith时如何正确匹配Date类型参数

问题原因

报错是类型不匹配导致的:
从ApplicationSession的定义可以看到,dateCreated、expiryDate都是Date类型,你的业务代码在处理API返回的日期字符串时,已经将其转换为了Date实例,而你在断言中传入的是字符串格式的日期,因此Jest比对不通过。

解决方案

方案1:直接传入Date实例做全等匹配

把断言中对应位置的日期字符串用new Date()包裹即可,同时建议把断言逻辑放到subscribe回调内避免时序问题,修改后的测试代码如下:

it('Then a session cookie is set from the API response', (done) => {
  subject.createSession().subscribe(() => {
    expect(cookiesService.setCookie).toHaveBeenCalledWith(
      ApplicationCookies.SESSION_COOKIE,
      {
        dateCreated: new Date('1996-10-15T04:35:32.000Z'),
        expiryDate: new Date('1996-10-15T15:35:32.000Z'),
        reference: 'some-reference'
      },
      { 
        expires: new Date('1996-10-15T15:35:32.000Z'), 
        path: "/", 
        sameSite: "strict", 
        secure: true 
      }
    );
    done();
  });
});

方案2:使用Jest不对称匹配器做灵活校验

如果你不需要严格匹配Date实例本身,只需要确认类型正确、时间值符合预期,可以用Jest的内置匹配器降低断言耦合,避免不同环境时区/日期序列化差异导致的测试不稳定:

it('Then a session cookie is set from the API response', (done) => {
  subject.createSession().subscribe(() => {
    // 先拿到setCookie的调用参数
    const [cookieName, sessionData, cookieOptions] = cookiesService.setCookie.mock.calls[0];
    
    // 分别校验各个字段
    expect(cookieName).toBe(ApplicationCookies.SESSION_COOKIE);
    expect(sessionData.reference).toBe('some-reference');
    // 校验日期类型和时间戳是否一致
    expect(sessionData.dateCreated).toBeInstanceOf(Date);
    expect(sessionData.dateCreated.getTime()).toBe(Date.parse('1996-10-15T04:35:32.000Z'));
    expect(sessionData.expiryDate.getTime()).toBe(Date.parse('1996-10-15T15:35:32.000Z'));
    expect(cookieOptions.expires.getTime()).toBe(Date.parse('1996-10-15T15:35:32.000Z'));
    expect(cookieOptions).toEqual(expect.objectContaining({
      path: "/", 
      sameSite: "strict", 
      secure: true 
    }));
    done();
  });
});

内容的提问来源于stack exchange,提问作者Marc Freeman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 20:36:09