Angular单元测试ngOnInit订阅

时间:2020-03-18 12:26:53

标签: angular jasmine

我首先使用Jasmine在Angular 9中进行单元测试。

我正在测试一个实现ngOnInit的简单组件:

export class HomeComponent implements OnInit {

      constructor(private router: Router
        , private authenticationService: AuthenticationService) { }

        ngOnInit(): void {
        this.authenticationService.checkIsAuthenticatedObservable()
        .subscribe(
          (isAuthenicated: boolean) => {
            if (isAuthenicated === true) {
              this.router.navigate(['/observation-feed']);
            }
          });
        }
      }

我在执行ngOnInIt生命周期挂钩时遇到了错误:

TypeError: Cannot read property 'subscribe' of undefined
    at <Jasmine>
    at HomeComponent.ngOnInit (http://localhost:9876/_karma_webpack_/main.js:8140:13)

我的测试规格设置如下:

describe('HomeComponent', () => {
  let component: HomeComponent;
  let fixture: ComponentFixture<HomeComponent>;
  let router: Router;
  let mockAuthenticationService;

  beforeEach(async(() => {
    mockAuthenticationService = jasmine.createSpyObj(['checkIsAuthenticatedObservable']);

    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule.withRoutes([
          // { path: 'login', component: DummyLoginLayoutComponent },
        ])
      ],
      declarations: [ HomeComponent ],
      providers: [
        { provide: AuthenticationService, useValue: mockAuthenticationService }
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(HomeComponent);
    router = TestBed.get(Router);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    mockAuthenticationService.checkIsAuthenticatedObservable.and.returnValue(of(false));
    fixture.detectChanges();
    // component.ngOnInit();

    expect(component).toBeTruthy();
  });
});

我尝试了各种组合设置模拟对象,并在初始化过程中的不同点调用fixture.detectChanges();component.ngOnInit();。我尝试过的任何方法都没有奏效。怎么了?

1 个答案:

答案 0 :(得分:1)

fixture.detectChanges部分中调用beforeEach时,Angular运行生命周期挂钩,并调用ngOnInit。这就是为什么会出错的原因-您在测试checkIsAuthenticatedObservable之后嘲笑fixture.detectChanges。 将您的模拟内容移到beforeEach之前的fixture.detectChanges部分,它将可以正常工作。 另外,对于Angular 9,您应该使用TestBed.inject而不是现在不推荐使用的TestBed.get

beforeEach(() => {
    fixture = TestBed.createComponent(HomeComponent);
    router = TestBed.inject(Router);
    component = fixture.componentInstance;
    mockAuthenticationService.checkIsAuthenticatedObservable.and.returnValue(of(false));
    fixture.detectChanges();
  });

  it('should create', () => {
    fixture.detectChanges();
    expect(component).toBeTruthy();
  });