jeudi 24 août 2017

How to inject another service to specific test case in angular testing

As in the above title question - is it possible to inject another instance of a service into specific test function? I mean situation, where in test suit I inject some service in beforeEach method.

Creating a stub:

let userServiceStub = {
  hasReadPermissions() { return true; },
  isUserInformationAvailable() { return true; },
  isUserRequestForbidden() { return true; }
};

In beforeEach method configuring test module:

TestBed.configureTestingModule({
  declarations: [
    SomeComponent
  ],
  providers: [{ provide: UserService, useValue: userServiceStub },
              { provide: AnotherService, useValue: anotherServiceStub }],
  schemas: [ NO_ERRORS_SCHEMA ]
}).compileComponents();

Then I have to test cases:

First where I would like to use service stub injected in TestBed

it('should render topbar when user has read permissions', () => {
  let topbar = debugElement.query(By.css('topbar'));
  expect(topbar).toBeTruthy();
});

Second where I want to use another stub of the same service:

let anotherUserServiceStub = {
  hasReadPermissions() { return false; },
  isUserInformationAvailable() { return false; },
  isUserRequestForbidden() { return true; }
};

it('should render appropriate message when user has not read permissions', 
   inject([UserService], (userService: UserService) => { <--- how to inject another user service stub here?
       let message = debugElement.query(By.css('h2'));
       expect(message).toBe('you have no permissions');
   }));

Or perhaps I'm trying to do it inappropriate way at all? Please point me a right way.

Aucun commentaire:

Enregistrer un commentaire