When running tests in Angular2+ using Karma and Jasmine, and subscripting to observables, that subscription (as I understand) is run asynchronously, so the test should be wrapped into an async
or fakeAsync
.
But we don't use async
not fakeAsync
, the tests passes, so my question is: isn't the code into the subscribe
used to be asynchronous? Why is the test passing? What is going on?
hello.component.ts
import { Component, Input, OnInit } from '@angular/core';
import {of} from 'rxjs';
@Component({
selector: 'hello',
template: `<h1>Hello {{name}}!</h1>`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent implements OnInit {
name: string;
ngOnInit() {
// Subscribing to sayName() to get a name
this.sayName().subscribe(name => this.name = name);
}
sayName() {
return of('Foo');
}
}
hello.component.spec.ts
import { CommonModule } from '@angular/common';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import {HelloComponent} from './hello.component';
describe('HelloComponent', () => {
let fixture: ComponentFixture<HelloComponent>;
let component: HelloComponent;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
CommonModule
],
declarations: [HelloComponent],
providers: [
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(HelloComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should have foo name', () => {
// Running out of async/fakeAsync
// and asserting we got the name
expect(component.name).toEqual('Foo');
});
});
You can also check in Stackblitz this example.