Code Monkey home page Code Monkey logo

nest-schedule's Introduction

Nest Logo

Nest Schedule

NPM Version Package License NPM Downloads

Description

This is a Nest module for using decorator schedule jobs.

Installation

$ npm i --save nest-schedule

Usage

import { Module } from '@nestjs/common';
import { ScheduleModule } from 'nest-schedule';

@Module({
  imports: [
    ScheduleModule.register(),
  ]
})
export class AppModule {
}
import { Injectable } from '@nestjs/common';
import { Cron, Interval, Timeout, NestSchedule } from 'nest-schedule';

@Injectable() // Only support SINGLETON scope
export class ScheduleService extends NestSchedule {    
  @Cron('0 0 2 * *', {
    startTime: new Date(), 
    endTime: new Date(new Date().getTime() + 24 * 60 * 60 * 1000),
  })
  async cronJob() {
    console.log('executing cron job');
  }
  
  @Timeout(5000)
  onceJob() {
    console.log('executing once job');
  }
  
  @Interval(2000)
  intervalJob() {
    console.log('executing interval job');
    
    // if you want to cancel the job, you should return true;
    return true;
  }
}

Dynamic Schedule Job

import { Injectable } from '@nestjs/common';
import { InjectSchedule, Schedule } from 'nest-schedule';

@Injectable()
export class ScheduleService {    
  constructor(
    @InjectSchedule() private readonly schedule: Schedule,
  ) {
  }
  
  createJob() {
    // schedule a 2s interval job
    this.schedule.scheduleIntervalJob('my-job', 2000, () => {
      console.log('executing interval job');
    });
  }
  
  cancelJob() {
    this.schedule.cancelJob('my-job');
  }
}

Distributed Support

1. Extend NestDistributedSchedule class

import { Injectable } from '@nestjs/common';
import { Cron, NestDistributedSchedule } from 'nest-schedule';

@Injectable()
export class ScheduleService extends NestDistributedSchedule {  
  constructor() {
    super();
  }
  
  async tryLock(method: string) {
    if (lockFail) {
      return false;
    }
    
    return () => {
      // Release here.
    }
  }
  
  @Cron('0 0 4 * *')
  async cronJob() {
    console.log('executing cron job');
  }
}

2. Use UseLocker decorator

import { ILocker, IScheduleConfig, InjectSchedule, Schedule } from 'nest-schedule';
import { Injectable } from '@nestjs/common';

// If use NestCloud, it supports dependency injection.
@Injectable()
export class MyLocker implements ILocker {
  private key: string;
  private config: IScheduleConfig;

  constructor(
    @InjectSchedule() private readonly schedule: Schedule,
  ) {
  }

  init(key: string, config: IScheduleConfig): void {
    this.key = key;
    this.config = config;
    console.log('init my locker: ', key, config);
  }

  release(): any {
    console.log('release my locker');
  }

  tryLock(): Promise<boolean> | boolean {
    console.log('apply my locker');
    return true;
  }
}
import { Injectable } from '@nestjs/common';
import { Cron, NestSchedule, UseLocker } from 'nest-schedule';
import { MyLocker } from './my.locker';

@Injectable()
export class ScheduleService extends NestSchedule {  
  @Cron('0 0 4 * *')
  @UseLocker(MyLocker)
  async cronJob() {
    console.log('executing cron job');
  }
}

API

class ScheduleModule

static register(config: IGlobalConfig): DynamicModule

Register schedule module.

field type required description
config.enable boolean false default is true, when false, the job will not execute
config.maxRetry number false the max retry count, default is -1 not retry
config.retryInterval number false the retry interval, default is 5000
config.waiting boolean false the scheduler will not schedule job when this job is running, if waiting is true

class Schedule

scheduleCronJob(key: string, cron: string, callback: JobCallback, config?: ICronJobConfig)

Schedule a cron job.

field type required description
key string true The unique job key
cron string true The cron expression
callback () => Promise<boolean> boolean If return true in callback function, the schedule will cancel this job immediately
config.startTime Date false The start time of this job
config.endTime Date false The end time of this job
config.enable boolean false default is true, when false, the job will not execute
config.maxRetry number false the max retry count, default is -1 not retry
config.retryInterval number false the retry interval, default is 5000
config.waiting boolean false the scheduler will not schedule job when this job is running, if waiting is true
config.immediate boolean false running job immediately

scheduleIntervalJob(key: string, interval: number, callback: JobCallback, config?: IJobConfig)

Schedule a interval job.

field type required description
key string true The unique job key
interval number true milliseconds
callback () => Promise<boolean> boolean If return true in callback function, the schedule will cancel this job immediately
config.enable boolean false default is true, when false, the job will not execute
config.maxRetry number false the max retry count, default is -1 not retry
config.retryInterval number false the retry interval, default is 5000
config.waiting boolean false the scheduler will not schedule job when this job is running, if waiting is true
config.immediate boolean false running job immediately

scheduleTimeoutJob(key: string, timeout: number, callback: JobCallback, config?: IJobConfig)

Schedule a timeout job.

field type required description
key string true The unique job key
timeout number true milliseconds
callback () => Promise<boolean> boolean If return true in callback function, the schedule will cancel this job immediately
config.enable boolean false default is true, when false, the job will not execute
config.maxRetry number false the max retry count, default is -1 not retry
config.retryInterval number false the retry interval, default is 5000
config.immediate boolean false running job immediately

cancelJob(key: string)

Cancel job.

Decorators

Cron(expression: string, config?: ICronJobConfig): MethodDecorator

Schedule a cron job.

field type required description
expression string true the cron expression
config.key string false The unique job key
config.startTime Date false the job's start time
config.endTime Date false the job's end time
config.enable boolean false default is true, when false, the job will not execute
config.maxRetry number false the max retry count, default is -1 not retry
config.retryInterval number false the retry interval, default is 5000
config.waiting boolean false the scheduler will not schedule job when this job is running, if waiting is true
config.immediate boolean false running job immediately

Interval(milliseconds: number, config?: IJobConfig): MethodDecorator

Schedule a interval job.

field type required description
milliseconds number true milliseconds
config.key string false The unique job key
config.enable boolean false default is true, when false, the job will not execute
config.maxRetry number false the max retry count, default is -1 not retry
config.retryInterval number false the retry interval, default is 5000
config.waiting boolean false the scheduler will not schedule job when this job is running, if waiting is true
config.immediate boolean false running job immediately

Timeout(milliseconds: number, config?: IJobConfig): MethodDecorator

Schedule a timeout job.

field type required description
milliseconds number true milliseconds
config.key string false The unique job key
config.enable boolean false default is true, when false, the job will not execute
config.maxRetry number false the max retry count, default is -1 not retry
config.retryInterval number false the retry interval, default is 5000
config.immediate boolean false running job immediately

InjectSchedule(): PropertyDecorator

Inject Schedule instance

UseLocker(locker: ILocker | Function): MethodDecorator

Make your job support distribution.

If you use NestCloud, the Locker will support dependency injection, or not use injection please.

Stay in touch

License

nest-schedule's People

Contributors

dependabot[bot] avatar devgavrilov avatar miaowing avatar ryanleecode avatar sandeepsuvit avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nest-schedule's Issues

Update to nestjs 6.0.0

npm WARN [email protected] requires a peer of @nestjs/common@^5.0.0 but none is installed. You must install peer dependencies yourself.

Please update to the newest version of nestjs. Thank you

How do I mock crons in test?

I am writing e2e testing. I need to disable the cron methods from automatic running, and trigger the methods in testing code manually. I suppose this is a common demand.

Such demand is unfortunately not supported by nest-schedule. Would you consider adding such function?

@Cron() decorator not working

Thanks for a great plugin for nest. @Interval decorator is working perfectly, but I can't start @Cron.

import { Injectable } from '@nestjs/common';
import { Cron, NestSchedule } from 'nest-schedule';

@Injectable()
export class ScheduleService extends NestSchedule {  
  constructor() {
    super();
  }
  
  @Cron('* * * * *')
  clear() {
    console.log('clear data ...');
  }
}

No log in console every minute.

Dependencies:

"dependencies": {
    "@nestjs/common": "^5.0.0",
    "@nestjs/core": "^5.0.0",
    ...
}

testing/debugging config

I have a Cron job that is scheduled to run everyday, Is there any way to do a test run of the command right now to see if it works as intended?

Setting values in extended class in tryLock

Instance properties in tryLock which are defined on subclass are never read properly in tryLock...please help i feel like i broke javascript

class ScheduleService extends NestDistributedSchedule {
  private runJobs = true
  constructor() {
    super()
  }
  
  async tryLock() {
    console.log(this.runJobs) // Always true even if setRunJobsFalse called
  }

  setRunJobsFalse() {
    this.runJobs = false;
    console.log(this.runJobs) // False
  }
}

applyDecorators is not a function

I'm using the lib as explained in the doc but I'm receiving this error message.
Any idea ?

D:\projects\project\node_modules@nestjs\schedule\dist\decorators\cron.decorator.js:8
return common_1.applyDecorators(common_1.SetMetadata(schedule_constants_1.SCHEDULE_CRON_OPTIONS, Object.assign(Object.assign({}, options), { cronTime })), common_1.SetMetadata(schedule_constants_1.SCHEDULER
_NAME, name), common_1.SetMetadata(schedule_constants_1.SCHEDULER_TYPE, scheduler_type_enum_1.SchedulerType.CRON));
^

TypeError: common_1.applyDecorators is not a function

Waiting for scheduled tasks in @Interval(delay) decorator

Does the module check if the previous execution of a task is still running when using the Interval decorator? Or even better, does it schedule it after the previous task has finished?
I tried to look at the code carefully but couldn't figure it out.

Should I somehow implement a subclass of NestDistributedSchedule with a custom tryLock function?

Dynamic cron job not wokring

Hi, i was trying to create a scheduler using dynamic cron job like so when my module initialises

@Injectable()
export class NotificationsService implements OnModuleInit {
    constructor(
        @InjectSchedule() private readonly schedule: Schedule,
    ) { }

    onModuleInit() {
        // Trigger every 10 seconds
        this.schedule.scheduleCronJob('cron', '*/10 * * * * *', () => {
            console.log('executing my custom interval job');
            return false;
        });
    }
}

When i start the server i get this error in the console

(node:45897) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'startTime' of undefined

which is weird because as per the method params the startTime and endTime are optional

scheduleCronJob(key: string, cron: string, callback: JobCallback, config?: ICronJobConfig): void;
...
export interface ICronJobConfig extends IJobConfig {
    startTime?: Date;
    endTime?: Date;
}

Am i missing something here?

Feature Request: No parallel runs for interval

It would be great if one could specify whether or not to start multiple runs for an interval.
This would be relevant if the task running in the function takes longer than the interval specified.

Right now one has to do the following:

@Interval(1000)
async job() {
  if (this.alreadyRunning) return false;
  this.alreadyRunning = true;

  // do stuff

  this.alreadyRunning = false;
  return false;
}

Suggestion: Add a flag in the config such as:

@Interval(1000, { singleExecution: true })

EDIT: Fixed wrong code.

`startTime` and `endTime` are not documented?

What do the following startTime and endTime configurations do, there are no associated API docs?

    @Cron('0 0 2 * *', {
        startTime: new Date(),
        endTime: new Date(new Date().getTime() + 24 * 60 * 60 * 1000),
    })

We can already set the scheduled interval with cron.

Logger, where is it used ?

Hi,

I was looking into overriding the logger but I can't see where it is actually used, the examples use console.log, is the logger injected or something ?

I would like to override the logger with my default one but I can't see where nest-schedule is actaully using the logger.

Can you elaborate a little

Cheers!

Service's constructor does not run with some specific condition

Hi,

Thanks for the package. I'm trying to create ScheduleService to schedule some task on a daily basis.

Here's my code

@Injectable()
export class ScheduleService extends NestSchedule {
        constructor() {
                super();
        }
 
        @Cron('* * * * *')
        async completeBookings() {
              console.log('testing cron');
        }
}

The above snippet runs just fine. But as soon as I start injecting one of my other services: BookingService. It seems like the constructor never runs. My debugger can hit the breakpoint placed on the constructor() but cannot hit the super() line.

@Module({
    providers: [BookingService],
    exports: [BookingService]
})
export class BookingModule {}

@Module({
     imports: [ScheduleModule.register(...), BookingModule],
     providers: [ScheduleService]
})
export class AppModule {}

The above setup is essential what I currently have.

Note: There are some specific services that I inject into the ScheduleService and the cron job runs just fine. There are some services that I inject and it just fails silently (does not run).

Is there anything that you can point me at?

Creating multiples jobs dynamically

here is my service..

import { Injectable } from '@nestjs/common';
import { InjectSchedule, Schedule, IJobConfig } from 'nest-schedule';

@Injectable()
export class ScheduleService {
    constructor(@InjectSchedule() private readonly schedule: Schedule) {}

    createJob(key: string, callback) {
            this.schedule.scheduleTimeoutJob(key, 5000, callback, { waiting: true });
    }

    cancelJob(key: string) {
        this.schedule.cancelJob(key);
    }
}

and when i call createJob several times with same parameters, the callback is executed one time and the other calls ends with this error:

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'status' of undefined
at Function.<anonymous> (/usr/src/app/node_modules/nest-schedule/dist/scheduler.js:99:40)

the waiting flag do not help in this case and i think use locks maybe is overcomplicating this case.
the expected behavior for me is that new jobs with same key shouldn't be created like what occurs at this method

public static queueJob(job: IJob) {

Class members are inaccessible in `tryLock`

Class members are inaccessible due to the class not being bound in the execution context of tryLock.

Following snippet explains what I mean.

import { Cron, NestDistributedSchedule } from 'nest-schedule';

export class Foo extends NestDistributedSchedule {
  public lock: boolean;

  constructor() {
    super();
    this.lock = false;
  }

  public async tryLock(method: string) {
    if (this.lock) { // runtime error, because `this` is undefined
      throw new Error();
    }
    this.lock = true;
    return () => {
      this.lock = false;
    };
  }

  @Cron('*/1 * * * * *')
  public async cron(): Promise<void> {
    console.log(new Date());
  }
}

const foo = new Foo();

Perhaps .bind should be added to
https://github.com/miaowing/nest-schedule/blob/master/lib/JobExecutor.ts#L19

Improve documentation for try / locking

Hi,

could you elaborate or provide more info on what happens when a lock can't be obtained for example

  async tryLock(method: string): Promise<TryRelease> {
    console.log("inside trylock")
    if (this.lock) {
      return false /// WHAT HAPPENS HERE ?
    }
    console.log("locking")
    this.lock = true
    return (): void => {
      console.log("releaseing")
      this.lock = false
    }
  }

How long does the job wait to obtain the lock, if the lock can't be obtained then it returns FALSE, does this mean the job fails or retries again ?

Thanks

config.waiting does not work

For a task that may need to run more than 5 minutes, I set config.waiting :true as I wish that the scheduler will not schedule job when this job is running.
@Cron('*/5 * * * *', {
startTime: new Date(),
waiting : true,
})

But seems the configuration does not work, the job still is able to run, and two same jobs run at the same time.

UnhandledPromiseRejectionWarning: #<JobRepeatException> is thrown when apply HRM

Nest throw this error when HRM is active

(node:11295) UnhandledPromiseRejectionWarning: #<JobRepeatException>
(node:11295) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 7)

Please help!

One cron is blocking another

In one of my microservices I have two modules with one @Cron in each of them:

// FeedModule
export class FeedService extends NestSchedule {
    // ...
    @Cron('00 30 6 * * *')
    async runCron() { ... }
}

// ArrivalModule
export class ArrivalService extends NestSchedule {
    // ...
    @Cron('* * * * *')
    async runCron() { ... }
}

ArrivalService check new data every minute. And when at 6:30 am FeedService tries to do it's job, it fails, because process is busy with ArrivalService job. What can you suggest? Thank you!

Dynamic cron job supporting locks - doens't seem to work ?

Hi,

I tried implementing the locks uisng decorators, this worked great but then i need to change to a dynamic cron job - so i can control when if it starts or not.. so i did

@Injectable()
export class CleanDbScheduleService extends NestDistributedSchedule {
  lock: boolean = false

  constructor(
    private readonly tokenService: TokenService,
    @InjectSchedule() private readonly schedule: Schedule,
    private readonly configService: ConfigService
  ) {
    super()
  }

  async tryLock(method: string): Promise<TryRelease> {
    console.log("inside trylock")
    if (this.lock) {
      return false
    }
    console.log("locking")
    this.lock = true
    return (): void => {
      console.log("releaseing")
      this.lock = false
    }
  }

  createJob(): void {
    this.schedule.scheduleIntervalJob("my-job", ms(this.configService.jobCleanDbInterval), () => this.cronJob())
  }

Works great, the job executes, but the locks are NOT being called.

Any ideas ?

Thanks

Distributed scheduling using redis ?

Hi,

Great module, loving it. I saw that you have a distributed lock class, i was wondering if you had planned some kind of integration with redis so that only 1 node would run the scheduled job or something similar ?

Thanks in advance

Processing Events

It would be nice to configure events on certain times within the scheduler.

ie:

  • schedule:start
  • schedule:error if an exception is thrown
  • schedule:done

always passing something like a

interface ScheduleEvent {
  startTime: Date,
  endTime?: Date,
  config: IJobConfig,
  error?: Error,
}

what do you think?

Error: Cannot find module '@nestjs/core/injector/constants'

Hi!

Install this great library and when I run the project I get this error:

Error: Cannot find module '@nestjs/core/injector/constants'

This is my package.json summarized:

"dependencies": {
    "@nestjs/common": "^5.4.0",
    "@nestjs/core": "^5.4.0",
    "nest-schedule": "^0.6.3",
    ....

Set time from config service to decorator

Is it possible to set time to decorator from configService which I use as dependency in my job module, for example this way:

export class JobService extends NestSchedule {
    private readonly logger = new Logger(JobService.name);

    constructor(
        private readonly configSerice: ConfigService,
    ) {
        super();
    }

    @Cron('10 0 * * *')
    async saveVoteResult2Db() {
        this.logger.log('Starting daily cronjob!!!');
    }

    @Interval(this.configSerice.syncInterval)
    async saveToRedis() {
        this.logger.debug('Data is synced with redis');
    }

Tests are running infinite time

Hi,

How I can completely disable the scheduler for test environment? I have tried defaults.enable = false, but it only ignore tasks, but the process is running.

Can't get interval/cron working

app.schedule.ts:

import { Injectable } from '@nestjs/common';
import { Cron, Interval, Timeout, NestSchedule } from 'nest-schedule';

@Injectable() // Only support SINGLETON scope
export class ScheduleService extends NestSchedule {  
  @Cron('*/1 * * * *', {
    startTime: new Date(),
  })
  async refreshMaterializedView() {
    console.log('runs interval');
  }

  @Timeout(5)
  onceJob() {
    console.log('executing once job');
  }

  @Interval(5)
  intervalJob() {
    console.log('executing interval job');

    // if you want to cancel the job, you should return true;
    return true;
  }
}

app.module.ts:

@Module({
  imports: [
    ProjectModule,
    ContactModule,
    TypeOrmModule.forRootAsync({
      useFactory: (config: ConfigService) => ({
        type: 'postgres',
        url: config.get('DATABASE_URL'),
        entities: [__dirname + '/**/*.entity{.ts,.js}'],
        synchronize: false,
      }),
      imports: [ConfigModule],
      inject: [ConfigService],
    }),
    ConfigModule,
    AuthModule,
    DispositionModule,
    OdataModule,
    AssignmentModule,
    DocumentModule,
    ScheduleModule.register(), // here
   ],
  controllers: [AppController],
})

Using Nest 6.0.0.

Not sure why but I'm not seeing any logging, or any indication that the class itself is instantiated. Anything I"m missing?

After upgrading to latest version 0.6.0 a JobRepeatException is thrown

Hey,

after upgrading to the latest version 0.6.0 I get the following exception:

(node:82651) UnhandledPromiseRejectionWarning: #<JobRepeatException>
(node:82651) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:82651) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I'm using the @Cron decorator. Where do I have to set the key or do I have to set the key at all?

Thanks for your help.

How do I upgrade from 0.4 to 0.6

I can't find a document or wiki page regarding upgrading. I got an error in this line after upgrading.

schedule.defaults.enable = false;

Is this the right new version?

ScheduleModule.register({ enable: false });

Can't create a simple service

Basic setup is throwing an error:

Class constructor NestSchedule cannot be invoked without 'new'

import { Cron, NestSchedule } from '@nestcloud/schedule';
import { Injectable } from '@nestjs/common';

@Injectable()
export class MyScheduler extends NestSchedule {
  constructor() {
    super();
  }

  @Cron('* * * * *')
  clear() {
    console.log('print log ...');
  }
}

import { Module } from '@nestjs/common';
import { MyScheduler } from './my.scheduler';

@Module({
  providers: [MyScheduler]
})
export class MyModule {}

Nestjs version: 5.5.0
Typescript version: 3.2.4

TimeoutJob after Server Reboot

I have a questions regarding the timeout jobs. Are they still executing, even after the server restarts? Or is there any way to persist a job, so it re-runs when the server reboots?

Thanks for your help!

Issues with injecting other services

Hello, first of all, this is a very nice module;

I've been using scheduler service in such way:

@Injectable()
export class ScheduleService extends NestSchedule {
  constructor(
    @InjectModel("Subscription") private readonly Subscription: Model<ISubscriptionInstance>,
    @Inject("NotificationService") private readonly notificationService: NotificationService
  ) {
    super();
  }

  @Interval(config.scheduleInterval, {
    immediate: true
  })
  async intervalJob() {
    // ...
  }
}

I've been able to successfully inject models, but I am unable to inject other service, as I am getting this error:

Nest can't resolve dependencies of the NotificationService (?). Please make sure that the argument at index [0] is available in the NotificationService context.

Is that limitation of the lib or I am doing something wrong? I've been able to inject services in other modules just fine.

Cannot read property 'subscriptionService' of undefined

Thanks for this great package.

I have built a schedule service and injected another service into it (service which I was successfully able to use in controllers etc).

@Injectable()
export class SubscriptionSchedulerService {

  constructor(private readonly subscriptionService: SubscriptionService) {
  }

  // each minute
  @Schedule({interval: 6000})
  async checkInvitationResponsesJob() {
      const inviteesEmails = await this.subscriptionService.getInviteesEmailsNotRespondedYet();
  }
}

When running it I receive: Cannot read property 'subscriptionService' of undefined

Are these schedule services initialized before others? Or am I missing something? I added it to providers in my module but I cannot simply call another injected service inside it...

Dynamic create corn job

Can I create dynamic corn job?
I want to create with several job with my nest api, and create a corn job with this api.
How to do that?

unit testing nest-schedule

Hi there,

I don't understand exactly how @InjectSchedule() works. Can you explain that?

We are using nest-schedule to run batch jobs in our application. I've written an abstract base.schedule class where schedules inherit from then. The constructor header looks like this:

export abstract class BaseSchedule implements OnModuleInit {

  protected constructor(
    @InjectSchedule() protected readonly schedule: Schedule,
  ) {
...
}

The question is how to I mock the schedule object in my unit tests?

I've tried like this but I still get an exception:

describe('BaseSchedule', () => {
  let service: BaseSchedule;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        BaseSchedule,
        { provide: Schedule, useValue: {} }
      ]
    }).compile();

    service = module.get<BaseSchedule>(BaseSchedule);
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });
});

This is the exception:
Error: Nest can't resolve dependencies of the BaseScheduleNotAbstract (?, JobService, Number, Number). Please make sure that the argument at index [0] is available in the _RootTestModule context.

So maybe when I understand @InjectSchedule() more clearly I know how to do the testing as well. :)
Thanks for your help!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.