测试期间在* ngIf语句中找不到按钮,因为该语句涉及一个模拟类

时间:2018-12-19 12:05:32

标签: angular testing

我正在构建一个应用程序,人们可以在其中使用Angular中的Github进行身份验证。我已经建立了一个按钮。尝试测试此按钮时,测试似乎找不到该按钮。我认为它与* ngIf语句有关系。

login.component.spec.ts:

    class MockAuthService implements Partial<AuthService> {
  isAuthenticated() {
    return 'Mocked';
  }


  loginwithGithubProvider() {
    return new Promise((resolve, reject) => resolve());
  }

  logout(): Promise<boolean | Observable<never> | never> {
    return new Promise(function(resolve, reject) { resolve(); });
  }
}


describe('LoginComponent', () => {
  let component: LoginComponent;
  let fixture: ComponentFixture<LoginComponent>;
  let componentService: AuthService;
  const routerSpy = jasmine.createSpyObj('Router', ['navigate']);
  const ghServiceSpy = jasmine.createSpyObj('GithubService', ['methodName']);

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        MatCardModule,
        AngularFireModule.initializeApp(environment.firebase),
        RouterModule.forRoot([{path: '', component: LoginComponent}]),
      ],
      declarations: [
        LoginComponent
      ],
      providers: [
        AuthService,
        AngularFirestore,
        AngularFireAuth,
        HttpClient,
        HttpHandler
      ]
    });
    TestBed.overrideComponent(LoginComponent, {
      set: {
        providers: [
          {provide: AuthService, useClass: MockAuthService},
          {provide: Router, useValue: routerSpy},
          {provide: GithubService, useValue: ghServiceSpy},
        ]
      }
    });

    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    componentService = fixture.debugElement.injector.get(AuthService);
  }));

  it('Logginbutton calls signInWithGithub', async(() => {
    spyOn(component, 'signInWithGithub');
    const button =  fixture.debugElement.nativeElement.querySelector('#signInWithGithub');
    button.click();
    fixture.whenStable().then(() => {
      expect(component.signInWithGithub).toHaveBeenCalled();
    });
  }));

login.component.html:

 <div *ngIf="authService.isLoggedIn; else loginTemplate">
    <h1>Welcome {{authService?.username}}</h1>
    <img src="{{ authService?.userDetails?.photoURL }} ">
    <br />
    <button mat-flat-button class="btn-github" id="logout" (click)="logout()">
      <i class="fab fa-github"></i> Stop authentication Github
    </button>
  </div>

  <ng-template #loginTemplate>
    <h1>FullProjectCloner</h1>
    <button mat-flat-button class="btn-github" id="signInWithGithub" (click)="signInWithGithub()">
      <i class="fab fa-github"></i> Authenticate with github
    </button>
    <p class="authError">{{this?.loginError}}</p>
  </ng-template> 

我得到的错误:

TypeError: Cannot read property 'click' of null

1 个答案:

答案 0 :(得分:0)

问题是您已经设置了所有内容,但没有调用必要的生命周期更改,以便在测试之前让Angular实际呈现任何内容。

简单的解决方法是在监视组件之后调用fixture.detectChanges()

我将其放在Stackblitz中,以确保它对您有用。在该Stackblitz中,只需注释掉fixture.detectChanges()即可看到问题。

这是Stackblitz的规格:

it('Logginbutton calls signInWithGithub', async(() => {
  spyOn(component, 'signInWithGithub');
  fixture.detectChanges();
  const button =  fixture.debugElement.nativeElement.querySelector('#signInWithGithub');
  button.click();
  expect(component.signInWithGithub).toHaveBeenCalled();
}));

您会注意到我也删除了对whenStable()的呼叫,因为这也不需要。