DEV Community

Smriti Rastogi
Smriti Rastogi

Posted on

1 1

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.'

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay