简体   繁体   中英

Mock Observable service on ngOnInit

PS This is first time I will be writing test cases.

Env details: - Angular 4.4.3

in component

currentToken: string;

constructor(private tokenService: TokenService){}

ngOnInit(): void {
   this.tokenService.getCurrentToken().subscribe((token: string) => {
      this.currentToken = token;
   });
}

in TokenService

export class TokenService {
   constructor(private router: Router) { }

   getCurrentToken(): Observable<string> {
      const token: string = sessionStorage.getItem("token");
      if (token) {
         return Observable.of(token);
      }else {
         this.router.navigate(['home']);
      }
   }
}

In spec.ts

describe("AccountComponent" , () => {
   let component: AccountComponent;
   let fixture: ComponentFixture<AccountComponent>;

   beforeEach(async(() => {
      TestBed.configureTestingModule({
        imports: [],
        declaration: [ TokenService ]
      }).compileComponents();
   }));

   beforeEach(() => {
     fixture = TestBed.createComponent(AccountComponent);
     component = fixture.createInstance;
     fixture.detectChanges();
     component.ngOnInit();
   });

   it("should create", () => {
     expect(component).toBeTruthy();
   });
});

This is simple test which will come when i used angular cli. As you may be already know that I am getting error like below.

"Cannot read property 'subscribe' of undefined"

This is common kind of method which i will writing in all new component.

TIA

You should be using a FakeService as below,

  • Define a fake class with the method returning some string.
  • The class
  • Inject the provider in the beforeEach()
  • In the it block modify it to the toBeDefined() as the component cannot be truthy

     describe("AccountComponent" , () => { let component: AccountComponent; let fixture: ComponentFixture<AccountComponent>; let tokenService : TokenService; class FakeTokenService { getCurrentToken(){ Observable.of('some string') } } beforeEach(async(() => { TestBed.configureTestingModule({ imports: [], declaration: [ ], providers: [ { provide: TokenService, useClass: FakeTokenService } ] }).compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(AccountComponent); component = fixture.createInstance; fixture.detectChanges(); fixture.debugElement.injector.get(TokenService); }); it("should create", () => { expect(component).toBeTruthy(); }); }); 

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