1

I'm trying to call a mocked service and update the user variable, but when I call the mocked service nothing changes?

I am generally struggling with testing, if there are any good resources to learn with angular2 I'm all ears.

let users = [{ name: 'Test', lastname: 'User' },  { name: 'Test2', lastname: 'User2' }];
let addedUsers = [{ name: 'blah', lastname: 'blah' },{ name: 'Test', lastname: 'User' },  { name: 'Test2', lastname: 'User2' }];

describe('Component: UserList', () => {
 beforeEach(() => {

 userServiceStub = {
  getUsers: () => {
    return Observable.of(users);
  },
  getUser: () => {
    return Observable.of(user);
  },
  addUser: () => {
    users.push({ name: 'blah', lastname: 'blah' });       
  }
};

TestBed.configureTestingModule({
  declarations: [UserListComponent],
  imports: [HttpModule],
  providers: [ 
      {provide: UsersService, useValue: userServiceStub },
      { provide: Router, useClass: RouterStub } 
    ]
});

app = fixture.debugElement.componentInstance; 
userService = fixture.debugElement.injector.get(UsersService);

it('should call addUser on button click', () => {
 let spy = spyOn(userService, 'addUser');     
 userService.addUser('argument'); 
 fixture.detectChanges();     
 expect(users).toEqual(addedUsers);
});

});
Mangopop
  • 329
  • 2
  • 12
  • This test doesn't make sense. All it does is testing the fake userServiceStub. And it fails because you've replaced the fake addUser() method by a jasmine spy. The test starts with `describe('Component: UserList'`. So it's supposed to test the UserList component. Not a fake service. – JB Nizet Nov 09 '16 at 17:54
  • Read this answer to understand the principle of mocking. http://stackoverflow.com/a/28783849/571407 – JB Nizet Nov 09 '16 at 17:56
  • I did have a click trigger in it block but stripped it to get to basics. So the spy was overwriting the stub, that should help. I will also clarify the test, although this was based on angular documentation 'testing a component with a dependency' – Mangopop Nov 10 '16 at 09:17
  • What I was trying to do was trigger a click that calls a service and adds an item to an array using the service. I am guessing this maybe too much testing in on go. – Mangopop Nov 10 '16 at 09:25

0 Answers0