Ben Winding
Ben Winding

Reputation: 11787

Angular-cli - Test Service

I'm using the angular-cli and have tried to get into the habbit of testing my services, but I can't seem to inject the service into the test here's my situation:

Angular2 Service

@Injectable()
export class AppService{
}

Karma Test - V1.3.0

Is this the correct syntax? It seems it's changed throughout the initial release of angular2.

describe('Tests', () => {
  beforeEach(() => [
    {provide: AppService, useClass: AppService}
  ]);

  it('should create an instance', inject([AppService], (service: AppService) => {
    expect(service).toBeTruthy();
  }));
});

Is this the correct syntax? It seems it's changed throughout the initial release of angular2.

Test Error

Tests should create an instance FAILED
    Error: No provider for AppService!

My Configuration

angular-cli: 1.0.0-beta.21
node: 6.5.0
os: win32 x64

Upvotes: 0

Views: 776

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 209004

If you want to inject it, you still need to use the TestBed to configure the Angular test environment

import { TestBed } from '@angular/core/testing';

beforeEach(() => TestBed.configureTestingModule({
  providers: [ {provide: AppService, useClass: AppService} ]
}));

*Note:** If the service doesn't have any other dependencies, you might just want to forget the Angular configuration, and just do an isolated test by instantiating the service yourself.

let service = new AppService();

See also:

Upvotes: 3

Related Questions