EugenSunic
EugenSunic

Reputation: 13703

How to test angular2 class/service with parameters inside constructor?

I have simple class with a method and constructor injection in the constructor:

import { WindowService } from '../path_to_serivce';

    export class ModeCheck {

      constructor(private windowRef: WindowService) { }

      public isMode(): boolean {
       logic ...
      }

    }

and my Interceptor testing spec.ts class (assume the imports are above)

describe('Interceptor', () => {

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [HttpClientTestingModule],
            providers: [
                {
                    provide: HTTP_INTERCEPTORS,
                    useClass: ModeInterceptor,
                    multi: true
                }, ModeCheck]
          });
    }); 


 });

The error which I get is Error: Can't resolve all parameters for ModeCheck: (?). Which basically says that I have to handle the constructor parameter in my test. How should I handle such issue?

Upvotes: 0

Views: 48

Answers (1)

R. Richards
R. Richards

Reputation: 25151

You need the @Injectable() decorator on a class that you are treating as a service that needs other services injected.

You need it above the export for your ModeCheck class.

Without this decorator on a service class, the constructor dependencies will not be resolved. It is actually recommended that you add that decorator to a service whether or not you are getting dependencies in the constructor. It is a clear way to tell anyone looking at the code that the class is a service.

Upvotes: 2

Related Questions