'Intermittent Jest expect fails on Date.toISOString()

I'm working on a project that today has 97 unit test suites with a total of 401 unit tests. In some of those unit tests, I need to assert that an object attribute is being correctly set.

type Object {
    expectedTimestamp?: string
}

type AnotherObject {
    expectedDate?: Date
}

...
function doUpdateSomething(anotherObject: AnotherObject): Object {
  const object: Object = {};
  object.expectedTimestamp = anotherObject.expectedDate?.toISOString();
  return object;
}

Sometimes when I run all the test suites, I get the following error:

    Expected: "2022-03-30T14:15:55.978Z"
    Received: "2022-03-30T14:15:55.979Z"

You can see that the difference is 1 milissecond. It can occur in several tests. It used to happen sometimes with the A test, sometimes with the B and C tests, sometimes it just didn't occur.

If I run a single test, this error never happens.

The tests are writen fallowing this structure:

describe('unit test', () => {
  it('assert date -> return true', () => {
    const obj: AnotherObject = Factory.buildAnotherObject();
    const response = doUpdateSomething(obj);
    expect(response.expectedTimestamp).toEqual(obj.expectedDate.toISOString());
  }),
})

The test command is declared in package.json like this: test:unit": "NODE_OPTIONS=\"--max-old-space-size=4096 \" npx --node-arg=--expose-gc jest --runInBand -c jest.unit.config.js --logHeapUsage --force-exit"

Observation: I can't share the original code. It belogs to a private company.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source