SimonTestNet / SimonTest

Repository for SimonTest questions and issues https://simontest.net
16 stars 2 forks source link

Inject and pull services from Injector within tests #7

Closed intellix closed 7 years ago

intellix commented 7 years ago

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

SimonTestNet commented 7 years ago

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

I'll do more research.

ManuelDeLeon commented 7 years ago

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".

intellix commented 7 years ago

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

ManuelDeLeon commented 7 years ago

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