ngOnInit上的Mock Observable服务

时间:2017-11-21 13:02:37

标签: angular unit-testing testing jasmine karma-jasmine

PS这是我第一次编写测试用例。

环境细节:   - Angular 4.4.3

组件

currentToken: string;

constructor(private tokenService: TokenService){}

ngOnInit(): void {
   this.tokenService.getCurrentToken().subscribe((token: string) => {
      this.currentToken = token;
   });
}
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']);
      }
   }
}

在规格

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();
   });
});

这是一个简单的测试,当我使用angular cli时会出现。你可能已经知道我会收到如下错误。

&#34;无法阅读财产&#39;订阅&#39;未定义&#34;

这是我将在所有新组件中编写的常用方法。

TIA

1 个答案:

答案 0 :(得分:1)

您应该使用FakeService,如下所示

  • 使用返回某些字符串的方法定义假类。
  • 班级
  • beforeEach()
  • 中注入提供程序
  • it块中将其修改为toBeDefined(),因为该组件不能真正

    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();
       });
    });