Testing a cron-job with JEST

Asked

Viewed 80 times

0

I have a javascript class that contains a function which initializes a cron job. To perform cron-job I used the Node-Cron library. But I can’t find a way to test the class and function.

The variables that control Node-cron are in a .env. For the tests I’m using jest Job is launched when the application is lifted (the file containing the class is imported and the class is already exported instantiated)

.env file

#CRON JOB
FREQUENCY_CRON='30 00 * * *'
TIMEZONE="America/Sao_Paulo"
SCHEDULED=true
INACTIVE_EXPIRATION_TIME=2592000000 #30 DAYS

Cronjob.js

class CronJob {
  constructor() {
    this.startJob();
  }

  async startJob() {
    cron.schedule(
      process.env.FREQUENCY_CRON,
      async () => {
        //DO SOME DATA PROCESSING 
      },
      {
        scheduled: process.env.SCHEDULED,
        timezone: process.env.TIMEZONE
      }
    );
  }
}

export default new CronJob();

1 answer

0

One of the best ways to isolate the scope of a unit of code is to use dependency injection, so you can simulate different test cases without needing too much configuration, in your case it would look something like this:

// importante exportar a classe também para permitir criar 
// uma instancia passando configurações, diferente do export default
export class CronJob {
  // o parâmetro configurations por padrão é um objeto vazio para permitir 
  // acessar as propriedades mesmo quando não há configurações, evitando o erro
  // "cannot read property of undefined"
  constructor(configurations = {}) {
    // o valor após o operador || é o padrão quando a configuração está ausente
    this.frequencyCron = configurations.frequencyCron || process.env.FREQUENCY_CRON;
    this.scheduled = configurations.scheduled || process.env.SCHEDULED;
    this.timezone = configurations.timezone || process.env.TIMEZONE;
    this.startJob();
  }

  async startJob() {
    cron.schedule(
      this.frequencyCron,
      async () => {
        //DO SOME DATA PROCESSING 
      },
      {
        scheduled: this.scheduled,
        timezone: this.timezone
      }
    );
  }
}

export default new CronJob();

This way, in the tests you can instantiate a new Cronjob with the settings you find most suitable for each specific case, example:

new CronJob({
  timezone: 'America/New_York'
})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.