Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

unit testing nest-schedule #37

Open
judos opened this issue Aug 23, 2019 · 1 comment
Open

unit testing nest-schedule #37

judos opened this issue Aug 23, 2019 · 1 comment

Comments

@judos
Copy link

judos commented Aug 23, 2019

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!

@mariusziemke
Copy link

Hi,

I've got the same issue and resolved it kind of simple I guess. Just import the ScheduleModule into the TestingModule.

e.g.

 const module = await Test.createTestingModule({
            imports: [
              ScheduleModule.register({enable : false}),
            ],
            providers: []
   ...

The parameter { enable: false } is basically stopping nest-schedule to execute the scheduled functions which comes in quite handy in my case as I only want to test my functions and not nest-schedule.

And by the way as far as I know InjectSchedule it is just a wrapper around the Inject function of nestjs. So basically it is just a custom decorator for dynamically injecting the service. Maybe have look here

I hope that this will help you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants