Search code examples
typescriptjestjs

Jest - How to test dates created miliseconds apart?


I'm writing a test to a function that extends an expiration date. As you can see below, there's a small difference between the moment I create or update the database document and the moment I make the assertion about the date:

    it('should extendExpirationDate', async () => {
        const document = documentBuilder.build();

        await testDatabase.fillCollections({ documents: [document] });

        let documents = await DocumentModel.find({});
        expect(documents[0].validUntil).toBe(moment().add(90, 'days').toDate());

        const documentDto: UpdateDocumentDto = {
            ...document,
            validUntil: moment().add(100, 'days').toDate(),
        };

        await documentService.extendExpirationDate(documentDto);

        documents = await DocumentModel.find({});
        expect(documents[0].validUntil).toBe(moment().add(100, 'days').toDate());
    });

Are there functions out there that could compare dates within a margin of error?
How can I make those tests not fail?

What did I try and what am I expecting?

I'm comparing dates that are milliseconds apart and the tests are failing.
I'm expecting the test to pass if the dates differ by milliseconds, but not days. I also want to avoid edge cases when one date is 2024-06-13T23:59:59.995Z and the other is 2024-06-14T00:00:00.002Z.


Solution

  • You are currently comparing generated values which depend on your system clock and on latency in your runtime execution, network, etc. — and this will not produce deterministic results. Instead, store the initial date of the created document and compare that to the date of the discovered document. Then do the same kind of comparison when you update the document's date:

    TS Playground

    it("should extendExpirationDate", async () => {
      const document = documentBuilder.build();
      let { validUntil } = document;
      await testDatabase.fillCollections({ documents: [document] });
    
      let documents = await DocumentModel.find({});
      expect(documents[0]?.validUntil).toEqual(validUntil);
    
      const DAY = 1000 * 60 * 60 * 24;
      validUntil = new Date(Date.now() + 100 * DAY);
    
      const documentDto: UpdateDocumentDto = { ...document, validUntil };
      await documentService.extendExpirationDate(documentDto);
    
      documents = await DocumentModel.find({});
      expect(documents[0]?.validUntil).toEqual(validUntil);
    });