【问题标题】:Angular unit test ngOnInit subscriptionAngular 单元测试 ngOnInit 订阅
【发布时间】:2020-03-18 20:57:02
【问题描述】:

我开始使用 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();。我所尝试的都没有奏效。这里出了什么问题?

【问题讨论】:

    标签: angular jasmine


    【解决方案1】:

    当您在beforeEach 部分调用fixture.detectChanges 时,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();
      });
    

    【讨论】:

    • 很高兴,我可以帮忙:)
    猜你喜欢
    • 2020-02-12
    • 1970-01-01
    • 2020-08-08
    • 2019-04-16
    • 2021-06-22
    • 2022-01-01
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多