'override injection token in unit test

I have a simple service with an Injection token that is used to provide some kind of configuration for the service. It's all working as expected. Although I wasn't able to test all the possible scenarios in single spec file. For some reason I'm not allowed to override the Injection token defined in providers.

token.config.ts

export interface MyConfig = {
    test: boolean;
}

export const ConfigToken = new InjectionToken<MyConfig>('MyConfig');

token.service.ts

@Injectable()
export class TokenRefreshService {

  public autoRefreshStarted = false;

  constructor(
    @Inject(ConfigToken) private config: MyConfig
  ) {}

  public initAutoRefresh(): void {
    if ( this.config.test === true ) {
      this.autoRefreshStarted = true;
    }
  }
}

token.service.spec.ts

describe('TokenRefreshService (with-auto-refresh)', () => {

  let service: TokenRefreshService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        {
          provide: ConfigToken,
          useValue: {}
        },
        TokenRefreshService
      ]
    });

    service = TestBed.get( TokenRefreshService );
  });

  it('should create an instance', () => {
    expect( service ).toBeDefined();
  });

  it('should not start auto-refresh', () => {

    service.initAutoRefresh();

    expect( service.autoRefreshStarted ).toBeFalsy();
  });


  it('should start auto-refresh', () => {
    TestBed.overrideProvider( ConfigToken, { useValue: { test: true  } }); /// doesn't override the config token at all ///

    service.initAutoRefresh();

    expect( service.autoRefreshStarted ).toBeTruthy();
  });

});

I would like to test scenarions when no config is provided to service or when config with an incorrect data is provided and so on. Therefore I really need a way to somehow override the injection token that is passed to the TokenService. But no matter what I tried, it just keeps returning the same data that are defined in the TestBed.configureTestingModule.

Am I doing something wrong? Or is there an easier way to do this?



Solution 1:[1]

Replace

imports: [
        {
          provide: ConfigToken,
          useValue: {}
        },
        TokenRefreshService
      ]

with:

providers: [
        {
          provide: ConfigToken,
          useValue: {}
        },
        TokenRefreshService
      ]

I guess importing a service never works

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dewey