Testing Angular
  • Overview
  • Overview
  • 1. Create a new Angular CLI application
  • 2. Run default tests
  • 3. Review the Angular CLI directory and testing tools set up
  • 4. Jasmine tests
  • 5. Add simple test
  • 6. Add simple failing test
  • 7. Add another test to check a property
  • 8. Test the Component logic using a mocked up Service
  • 9. Test the Component logic using SpyOn
  • 10. TestBed and Fixtures
Powered by GitBook
On this page

9. Test the Component logic using SpyOn

SpyOn is a Jasmine feature that allows dynamically intercepting the calls to a function and change its result. This example shows how spyOn works, even if we are still mocking up our service.

  • Change the Mockup service so getNames returns nothing

src/app/app.component.spec.ts
...

  beforeEach(() => {
    appService = { getNames: () => of([]) };
    component = new AppComponent(fakeAppService);
  });
  
...
  • Add a new Test case

src/app/app.component.spec.ts
import { of } from 'rxjs';

import { AppComponent } from './app.component';
import { AppService } from './app.service';
import { Name } from './app.models';

describe(`Component: App Component`, () => {
  let appService: AppService;
  let component: AppComponent;

  beforeEach(() => {
    appService = { getNames: () => of([]) };
    component = new AppComponent(appService);
  });

  it('add 1+1 - PASS', () => {
    expect(1 + 1).toEqual(2);
  });

  it(`title equals 'testing'`, () => {
    expect(component.title).toEqual('testing');
  });

  it(`Expect service to return a single name`, () => {
    component.ngOnInit();
    component.names$.subscribe((names: Name[]) => {
      expect(names).toEqual([]);
    });
  });

  it(`Expect service to return a single name`, () => {
    const fakeNames = [{ name: 'FAKE_NAME' }];
    spyOn(appService, 'getNames').and.returnValue(of(fakeNames));
    component.ngOnInit();

    component.names$.subscribe((names: Name[]) => {
      expect(names).toEqual(fakeNames);
    });
  });
});
Previous8. Test the Component logic using a mocked up ServiceNext10. TestBed and Fixtures

Last updated 6 years ago