Unable to test schedule via jest.useFakeTimers()

Author: jira-zzCreated Dec 3, 2024Updated Dec 3, 2024

Hello,

my app is using node-schedule, and I want to test it using jest fakeTimers. I'm sure, I'm doing something wrong, but the scheduled job won't execute no matter how I write the tests. I feel, I tried every possible suggestion I could find on Stack Overflow. I would appreciate any help.

Here is a minimal example:

bash
import { scheduleJob } from "node-schedule";
import { DateTime } from "luxon";

export class NST {

  startWork() {
    console.log("working");
  }

  scheduleIt() {
    const dt = DateTime.now().plus({seconds: 4}).toJSDate();
    scheduleJob(dt, () => { this.startWork() });
  }


}

const nst = new NST();

nst.scheduleIt()

and a test

import { NST } from "../p";

describe("test", () => {


   it("should work", () => {
    jest.useFakeTimers();
    const s = new NST();
    const spy = jest.spyOn(s, 'startWork');
    const myMock = jest.fn();
    s.startWorks = myMock;
    s.scheduleIt();
    jest.advanceTimersByTime(5000);
    expect(myMock).toHaveBeenCalled();

   });
});

~

Source: node-schedule/node-schedule