【问题标题】:Subscribe for component using mock service is not being executed during test在测试期间未执行使用模拟服务订阅组件
【发布时间】:2018-09-29 05:39:28
【问题描述】:

我有一个使用服务的组件,您可以想象,该服务是在另一个类中实现的。对于这个组件的测试,我已经模拟了这个服务。基本上,这是我订阅服务的组件文件:

this.tokenManagerService.retrieveToken().subscribe(token => {
  const tokenRetrieved = JSON.parse(token);
  console.log(tokenRetrieved);
  if (tokenRetrieved.error) {
    this.error = tokenRetrieved.error;
}

这是我模拟服务的组件的测试配置:

beforeEach(() => {
  tokenManagerServiceMock = new TokenManagerServiceMock();
  TestBed.configureTestingModule({
    declarations: [ AuthenticationComponent ],
    imports: [ FormsModule, HttpModule,RouterTestingModule.withRoutes([]) ],
    providers: [
      { provide: TokenManagerService, useValue: tokenManagerServiceMock }
    ]
  });
  TestBed.overrideComponent(AuthenticationComponent, {
  set: {
    providers: [
      { provide: TokenManagerService, useValue: tokenManagerServiceMock }
    ]
  }
});

这是我的测试:

it('should detect white field message', () => {
  fixture.whenStable().then(() => {
    inputEmail.nativeElement.value = faker.internet.email();
    inputEmail.nativeElement.dispatchEvent(new Event('input'));
    inputPassword.nativeElement.value = faker.internet.password();
    inputPassword.nativeElement.dispatchEvent(new Event('input'));
    loginButton.click();
    fixture.detectChanges();
  });
});

loginButton.click()被执行时,它应该会触发onSubmit中的输入,这实际上正在发生。但是为什么subscribe方法没有被执行呢?

OBS:这是组件订阅的模拟服务的方法:

public retrieveToken(): Observable<string> {
  return this.subject.asObservable();
}

编辑: @picciano 建议此主题已在此 issue 中解决。但实际上,不是。我很确定代码正在调用onSubmit 中的方法,只是没有调用使用subscribe 的方法,而在另一个主题中,他想知道该方法是否被调用。另外,正在订阅的方法正在执行,我已经在里面打印了。

【问题讨论】:

标签: angular rxjs angular-cli karma-jasmine


【解决方案1】:

一般来说,如果您使用 whenStable(),您应该使用 async() 进行包装:https://codecraft.tv/courses/angular/unit-testing/asynchronous/#_code_async_code_and_code_whenstable_code

【讨论】:

  • 我看到这被否决了,但 FWIW 你应该仍然使用 async()。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-16
  • 2017-09-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多