简体   繁体   中英

Karma/Jasmine: Unable to test a service method being called inside a component in Angular 4

I am new to karma/jasmine and trying to test a code where a component method calls a service method and expects a value in return.

Component
Here is a small component which I created. isLoginRequired() gets called within ngOnInit() which further executes this.service.checkAuthentication() .

export class AppComponent implements OnInit {
  public title = 'app';
  public showLoginBtn = true;

  constructor(private service: CustomService) {}

  ngOnInit() {
    localStorage.setItem('key', '12345');
    this.title = 'name changed';
    this.isLoginRequired();
  }

  isLoginRequired() {
    this.showLoginBtn = this.service.checkAuthentication();
  }
}

Service
This is the custom service inside which the method checkAuthentication() resides.

@Injectable()
export class CustomService {

  constructor() { }

  checkAuthentication(): boolean {
    return !!localStorage.getItem('key');
  }
}

Specs
This is the spec file where I am writing the unit test cases. Please refer to test case #4 .

describe('App component testing', () => {

  let component: AppComponent;
  let service: CustomService;
  let fixture;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent,
        CustomPipe,
        CustomDirective
      ],
      providers: [
        CustomService
      ]
    }).compileComponents();
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.debugElement.componentInstance;
    service = TestBed.get(CustomService);
  });

  // test case #1
  it('component creation', () => {
    expect(component).toBeTruthy();
  });

  // test case #2
  it('has title "app"', () => {
    expect(component.title).toBe('app');
  });

  // test case #3
  it('isLoginRequired is triggered', () => {
    spyOn(component, 'isLoginRequired');
    component.ngOnInit();
    expect(component.isLoginRequired).toHaveBeenCalled();
  });

  // test case #4
  it('service.checkAuthentication is triggered', () => {
    spyOn(component, 'isLoginRequired');
    spyOn(service, 'checkAuthentication');
    component.ngOnInit();
    expect(component.isLoginRequired).toBeTruthy();
    expect(service.checkAuthentication).toHaveBeenCalled();
  });
});

Errors

Error: Expected spy checkAuthentication to have been called.

I really need help here. Thanks in advance!

Change spyOn(component, 'isLoginRequired'); into spyOn(component, 'isLoginRequired').and.callThrough();

The default is to not execute the Methode.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM