Skip to content

[Bug]: Cookie expiration for document.cookie does not use the date set by jest.setSystemTime #15727

@DamianPereira

Description

@DamianPereira

Version

30.0.4

Steps to reproduce

  1. Clone repo : https://github.com/DamianPereira/jest-cookie-repro
  2. Run npm install
  3. Run npm test
  4. Test should pass since expire date for cookie is in the future.

Copy of the spec in the repo

describe("cookie expiring", () => {
    it("should not be expired when expire date is in the future", () => {
        jest.useFakeTimers();
        jest.setSystemTime(new Date("Mon, 01 Jan 2023 12:00:00 GMT"));
        document.cookie = "foo=bar; expires=Mon, 02 Jan 2023 12:00:00 GMT";
        expect(document.cookie).toBe("foo=bar");
    });
});

Expected behavior

Test in repo passes. When setting system time, that time should be used to define when cookies expire, so a cookie that expires on 2 Jan 2024 should still be visible when the current date is 1 Jan 2024.

Actual behavior

Cookies expire according to real system time, not mocked time. If the expire date is set in the future (for example 2026), then cookie still exists.

Additional context

This is a duplicate of #11585, it was closed because of no activity, but it's still happening.

The workaround specified in last ticket does not work on typescript, a small change is required:

Object.defineProperty(document, 'cookie', {
  get () {
    return jsdom.cookieJar.getCookieStringSync(this.URL, { http: false, now: new Date() })
  },

  set (cookieStr) {
    jsdom.cookieJar.setCookieSync(String(cookieStr), this.URL, { http: false, ignoreError: true })
  },
})

Note how now is a Date and not Date.now() like written in #11585. I also had to add the following global.d.ts file to allow ts to work with global jsdom:

import { JSDOM } from 'jsdom'

declare global {
  const jsdom: JSDOM
}

Source for this snippet: github.com/simon360/jest-environment-jsdom-global/issues/5

Environment

System:
    OS: macOS 15.5
    CPU: (14) arm64 Apple M4 Max
  Binaries:
    Node: 22.17.0 - ~/.asdf/installs/nodejs/lts/bin/node
    Yarn: 1.22.22 - /opt/homebrew/bin/yarn
    npm: 10.9.2 - ~/.asdf/plugins/nodejs/shims/npm
    pnpm: 10.12.4 - /opt/homebrew/bin/pnpm
  npmPackages:
    jest: ^30.0.4 => 30.0.4

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions