DEV Community

Smriti Rastogi
Smriti Rastogi

Posted on

Is this how you test Node cron jobs?

I have a node cron job in my application that looks something like this:


const taskOne = (time) => {
   const loadData = schedule(time , ()=>{

}
loadData.start();

}

taskOne("23 04 * * 0-6")
Enter fullscreen mode Exit fullscreen mode

*The way I wrote it this was because the same logic runs two times in a day so did not want to write the logic again.
*

The way I am trying to test is:

describe("cron jobs", () => {
    let year, month, day;
    beforeAll(() => {
      const date = new Date();
      year = date.getFullYear();
      month = String(date.getMonth()).padStart(2, "0");
      day = String(date.getDate()).padStart(2, "0");
    });

    it("run taskOne node cron job", async () => {
      const currentHour = new Date().getHours();
      let currentMinutes = String(new Date().getMinutes()).padStart(2, "0");
      if (currentMinutes == `60`) currentMinutes = `01`;
      taskOne(`${currentMinutes} ${currentHour} * * 0-6`);
      setTimeout(() => {
        //expect statements
        done();
      }, 300000);
    });
Enter fullscreen mode Exit fullscreen mode

The above test passes but these cron jobs take a long time to finish (could be 30 -60 minutes) so it is getting difficult to decide when should I do the assertions using expect statement. Currently I am doing it after a wait for 5 minutes to verify some of the tasks that usually completes within that time.

Another issue is how to stop these cron jobs after I do my assertions otherwise jest throws below warnings:Jest did not exit one second after the test run has completed.

'This usually means that there are asynchronous operations that weren't stopped in your tests.'

Top comments (0)