简体   繁体   中英

SpyOn not working properly - Angular

When I run my specs I am receiving a failure with my integration test that indicates my spyOn for Auth0 service auth.authenticated() is not setting the correct return value. Basically, this spec should be returning a truthy value (id_token) in order for the Log Out button to be displayed. Since it is still showing the Log In button, I assuming the null value is sticking instead of being set to the string in the AuthResponse variable.

Am I missing something in my setup? Any help would greatly be appreciated.

//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();
    }));
  });
});

Template for the Navbar component

//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 Service

//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');
  }
}

测试输出

在此处输入图片说明

After getting hints from @JBNizet, I was not instantiating the AuthService from TestBed and I decided to make a separate spyOn for each response. Though it doesn't look DRY, it works.

Here is the solution for 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');
    }));
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM