【问题标题】:SpyOn not working properly - AngularSpyOn 无法正常工作 - Angular
【发布时间】:2017-10-12 02:27:03
【问题描述】:

当我运行我的规范时,我的集成测试失败,表明我的 spyOn for Auth0 service auth.authenticated() 没有设置正确的返回值.基本上,该规范应该返回一个 truthy 值 (id_token),以便显示 Log Out 按钮。由于它仍然显示 Log In 按钮,我假设 null 值是固定的,而不是设置为 AuthResponse 变量中的字符串。

我的设置是否遗漏了什么?我们将不胜感激。

//navbar.component.ts
import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';

@Component({
  selector: 'afn-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {

  constructor(private auth: AuthService) { }

  ngOnInit() {
  }

}


//navbar.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { NavbarComponent } from './navbar.component';
import { AuthService } from '../auth.service';

describe('NavbarComponent', () => {
  let component: NavbarComponent;
  let navbar: NavbarComponent;
  let fixture: ComponentFixture<NavbarComponent>;
  let auth: AuthService;
  let authResponse: string;


  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ NavbarComponent ],
      providers: [ AuthService ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(NavbarComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });


  beforeEach(() => {
    auth = new AuthService();
    spyOn(auth, 'authenticated').and.returnValue(authResponse);
  });

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

  describe('Unauthenticated user', () => {

    beforeEach(() => {
      authResponse = null;
      navbar = fixture.debugElement.componentInstance;
    });

    it('should should display "Log In" button', async(() => {
      const compiled = fixture.debugElement.nativeElement;
      expect(compiled.querySelector('button').textContent).toContain('Log In');
    }));

    it('should receive a falsy response from auth.authenticated', async(() => {
      navbar.ngOnInit();
      expect(auth.authenticated()).toBeFalsy();
    }));
  });

  describe('Authenticated user', () => {

    beforeEach(() => {
      authResponse = '23kjsfdi723bsai7234dfsfghfg';
      navbar = fixture.debugElement.componentInstance;
    });

    it('should display "Log Out" button', async(() => {
      fixture.detectChanges();
      const compiled = fixture.debugElement.nativeElement;
      expect(compiled.querySelector('button').textContent).toContain('Log Out');
    }));

    it('should receive a truthy response from auth.authenticated', async(() => {
      navbar.ngOnInit();
      expect(auth.authenticated()).toBeTruthy();
    }));
  });
});

导航栏组件的模板

//navbar.component.html
    <div class="navbar-header">
      <a class="navbar-brand" href="#">Auth0 - Angular 2</a>
      <button class="btn btn-primary btn-margin" (click)="auth.login()" *ngIf="!auth.authenticated()">Log In</button>
      <button class="btn btn-primary btn-margin" (click)="auth.logout()" *ngIf="auth.authenticated()">Log Out</button>
    </div>

Auth0 服务

//auth.service.ts
import { Injectable } from '@angular/core';
import { tokenNotExpired } from 'angular2-jwt';
import Auth0Lock from 'auth0-lock';

@Injectable()
export class AuthService {
  // Configure Auth0
  lock = new Auth0Lock('hcDsjVxfeZuAVWg39KIWFXV63n8DjHli', 'afn.auth0.com', {});

  constructor() {
    // Add callback for lock `authenticated` event
    this.lock.on('authenticated', (authResult) => {
      localStorage.setItem('id_token', authResult.idToken);
    });
  }

  public login() {
    // Call the show method to display the widget.
    this.lock.show();
  }

  public authenticated() {
    // Check if there's an unexpired JWT
    // This searches for an item in localStorage with key == 'id_token'
    return tokenNotExpired('id_token');
  }

  public logout() {
    // Remove token from localStorage
    localStorage.removeItem('id_token');
  }
}

【问题讨论】:

  • 这毫无意义。由 Angular 创建并注入到您的组件中的服务实例与您在 beforeEach 函数中创建的服务实例不同。您需要从 TestBed(即实际的)获取 AuthService,并监视该实例。此外,您已经将间谍配置为返回其先前值之后,为 authResponse 分配一个新值不会有任何效果。
  • 所以除了不实例化正确的 AuthService 之外,为了从 spyOn 获得正确的返回,我必须为每个响应创建单独的间谍?

标签: angular karma-jasmine angular-cli auth0


【解决方案1】:

从@JBNizet 获得提示后,我没有从 TestBed 实例化 AuthService,我决定为每个响应创建一个单独的 spyOn。虽然它看起来并不干燥,但它确实有效。

这里是 navbar.component.spec.ts 的解决方案:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { NavbarComponent } from './navbar.component';
import { AuthService } from '../auth.service';

describe('NavbarComponent', () => {
  let component: NavbarComponent;
  let navbar: NavbarComponent;
  let fixture: ComponentFixture<NavbarComponent>;
  let auth: AuthService;
  let falsyResponse = null;
  let truthyResponse = '23kjsfdi723bsai7234dfsfghfg';

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ NavbarComponent ],
      providers: [ AuthService ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(NavbarComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  beforeEach(() => {
    auth = TestBed.get(AuthService);
  });

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

  describe('Unauthenticated user', () => {

    beforeEach(() => {
      spyOn(auth, 'authenticated').and.returnValue(falsyResponse);
      navbar = fixture.debugElement.componentInstance;
    });

    it('should receive a falsy response from auth.authenticated', async(() => {
      navbar.ngOnInit();
      expect(auth.authenticated()).toBeFalsy();
    }));

    it('should should display "Log In" button', async(() => {
      const compiled = fixture.debugElement.nativeElement;
      expect(compiled.querySelector('button').textContent).toContain('Log In');
    }));
  });

  describe('Authenticated user', () => {

    beforeEach(() => {
      spyOn(auth, 'authenticated').and.returnValue(truthyResponse);
      navbar = fixture.debugElement.componentInstance;
    });

    it('should receive a truthy response from auth.authenticated', async(() => {
      navbar.ngOnInit();
      expect(auth.authenticated()).toBeTruthy();
    }));

    it('should display "Log Out" button', async(() => {
      fixture.detectChanges();
      const compiled = fixture.debugElement.nativeElement;
      expect(compiled.querySelector('button').textContent).toContain('Log Out');
    }));
  });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-11
    • 2018-09-13
    • 2015-03-06
    • 2020-03-09
    • 2018-04-22
    • 2020-11-04
    • 2018-07-03
    相关资源
    最近更新 更多