SimonTest icon indicating copy to clipboard operation
SimonTest copied to clipboard

Inject and pull services from Injector within tests

Open intellix opened this issue 9 years ago • 4 comments

Currently, mocks are created and referenced globally within a test.

The recommended approach is to fetch them from the injector: https://angular.io/docs/ts/latest/guide/testing.html#!#service-from-injector

Currently:

describe('onSubmit', () => {
  it('should call activate if valid', () => {
    spyOn(userServiceStub, 'activate');
    component.onSubmit();
    expect(userServiceStub.activate).toHaveBeenCalled();
  });
});

Recommended:

describe('onSubmit', () => {
  it('should call activate if valid', 
    inject([UserService], (userService: UserService) => {
      spyOn(userService, 'activate');
      component.onSubmit();
      expect(userService.activate).toHaveBeenCalled();
    });
});

When I log out the method being spied upon within my service, it's not a spy. But if I use the injector to fetch it first and then spy, it does work

intellix avatar Apr 10 '17 13:04 intellix

Reading the docs it seems that the recommended way is: userService = fixture.debugElement.injector.get(UserService);

I'll do more research.

SimonTestNet avatar Apr 10 '17 15:04 SimonTestNet

I'll leave it as it is for now; until someone points out a problem with the current implementation or a benefit of using something different.

I acknowledge that using the recommended way wouldn't hurt, but in general I have a problem with doing/changing things "just because".

ManuelDeLeon avatar Apr 15 '17 14:04 ManuelDeLeon

It's also how they look if you generate tests using Angular CLI :)

intellix avatar Apr 15 '17 19:04 intellix

fyi, v0.12.0 now uses injectors. See https://github.com/SimonTestNet/SimonTest/issues/10

ManuelDeLeon avatar Jun 06 '17 23:06 ManuelDeLeon