0

I have a component that uses a service and, as you can imagine, this service is implemented in another class. For the test of this component, I already mocked the service. Basically, this is my component file where I subscribe to the service:

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

And this is my test configuration for the component where I mock the service:

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

And this is my test:

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

When the loginButton.click() is executed, it should trigger the enter in the onSubmit, which actually is happening. But why the subscribe method is not being executed?

OBS: This is the method for the mock service where the component is subscribing:

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

EDIT: @picciano suggested that this topic was already solved in this issue. But actually, not. What I pretty sure that the code is calling the methods inside onSubmit, just not calls the method that using subscribe, while in the other topic, he wants to know if the method is called or not. Also, the method that is being subscribed is executing, I already printed inside it.

olegario
  • 711
  • 2
  • 16
  • 35

1 Answers1

-1

In general, if you're using whenStable() you should be wrapping with async(): https://codecraft.tv/courses/angular/unit-testing/asynchronous/#_code_async_code_and_code_whenstable_code