elzoy
elzoy

Reputation: 5435

Testing a service - how to inject tested service only once

  it('should ...', inject([XService], (service: XService) => {
    expect(service).toBeTruthy();
  }));

This way I can use service inside 'it'. There is a lot more 'it' and I don't want to inject service every time. I would like to inject the service once somewhere at the start (in beforeEach for example) but I can't. xService has a lot of dependencies inside constructor which I'd like to get also.

The only way I could've done this was to set all those values inside the first 'it'.

let xService: XService;
let yService: YService;
let zService: ZService;

beforeEach(() => ...);

  it('should ...', inject([XService], (service: XService) => {
    xService = service;
    yService = xService['yService'];
    zService = xService['zService'];

    expect(xService).toBeTruthy();
  }));

But personally I thinks this is an ugly solution. Can I in some way move it to beforeEach?

Upvotes: 1

Views: 423

Answers (1)

Mezo Istvan
Mezo Istvan

Reputation: 2782

Instead of inject, try using TestBed.get(). It's basically the same functionality, and your problem can be solved with it easily:

let xService: XService;
let yService: YService;
let zService: ZService;

beforeEach( () => {

    TestBed.configureTestingModule( ... ).compileComponents();

    xService = TestBed.get( XService );
    yService = TestBed.get( YService );
    zService = TestBed.get( ZService );

} );

it( 'should ...',() => {

    expect( xService instanceof XService ).toBe( true );

} );

Upvotes: 2

Related Questions