Angular 单元测试 ngOnInit 订阅

Min*_*nto 1 jasmine angular

我开始使用 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']);
            }
          });
        }
      }
Run Code Online (Sandbox Code Playgroud)

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

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

我的测试规范设置如下:

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();
  });
});
Run Code Online (Sandbox Code Playgroud)

我尝试了设置模拟对象以及在初始化的不同点调用fixture.detectChanges();和的各种组合。component.ngOnInit();我尝试过的方法都不起作用。这里出了什么问题?

Mac*_*zak 8

fixture.detectChanges当您在该部分中调用时beforeEach,Angular 会运行生命周期挂钩并被ngOnInit调用。这就是为什么你会收到错误 - 你checkIsAuthenticatedObservable在测试中在第一个fixture.detectChanges. 将您的模拟移至beforeEach之前的部分,fixture.detectChanges它将正常工作。另外,对于 Angular 9,您应该使用现已弃用的 TestBed.injectTestBed.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();
  });
Run Code Online (Sandbox Code Playgroud)