Angular 4:测试 window.location.href 是否已被调用

lka*_*ono 5 testing angular

我有一个AuthGuard负责检测用户是否登录的服务。如果没有登录,我会将用户重定向到我们的 oauth 提供程序 URL。

import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';

import { environment } from './../../environments/environment';
import { Session } from './../core/security/session.service';

@Injectable()
export class AuthGuard implements CanActivate {
  /**
   * Class constructor.
   * @constructor
   *
   * @param {Session} - Instance of session.
   */
  constructor(private session: Session) {}

  /**
   * Method to implements from CanActivate interface.
   * Check if a user is authenticated.
   *
   * @return {boolean}
   */
  canActivate(): boolean {
    if (this.session.isActive()) {
      return true;
    }

    this.redirectToProvider();
    return false;
  }

  /**
   * Redirect to Identity unauthorized url.
   */
  private redirectToProvider() {
    const unauthorizeUrl = environment.api.identity.unauthorizeUrl;
    window.location.href = unauthorizeUrl;
  }
}
Run Code Online (Sandbox Code Playgroud)

我想知道window.location.href当 Session 不存在时是否已被调用。这是我到目前为止所做的:

import { TestBed, async, inject } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';

import { AuthGuard } from './auth-guard.service';
import { Session } from './../core/security/session.service';

describe('AuthGuard', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        AuthGuard,
        Session
      ],
      imports: [RouterTestingModule]
    });
  });

  describe('.canActivate', () => {
    describe('active session', () => {
      it('returns true',
        async(inject([AuthGuard, Session], (guard, session) => {
          session.set({ name: 'user' });

          expect(guard.canActivate()).toBeTruthy();
        })
      ));
    });

    describe('no session', () => {
      it('redirects the user',
        async(inject([AuthGuard, Session], (guard, session) => {
          spyOn(window.location, 'href');
          session.destroy();

          expect(guard.canActivate()).toBeFalsy();
          expect(window.location.href).toHaveBeenCalled();
        })
      ));
    });
  })
});
Run Code Online (Sandbox Code Playgroud)

但它给了我以下错误:

Failed: <spyOn> : href is not declared writable or has no setter
Run Code Online (Sandbox Code Playgroud)

有没有办法模拟 window 对象来实现这一点,或者我是否需要依赖一些特殊的类来处理这种重定向,以便我可以在测试中注入它们?

小智 7

您可以window作为注入令牌注入。AngularDOCUMENT在 @angular/common 中还有一个DI 令牌,您可以直接将其与document.location.href.

import { InjectionToken } from '@angular/core';

export const WindowToken = new InjectionToken('Window');
export function windowProvider() { return window; }
Run Code Online (Sandbox Code Playgroud)

添加它app.module.ts

providers: [
    ...
    { provide: WindowToken, useFactory: windowProvider }
  ]
Run Code Online (Sandbox Code Playgroud)

并将其注入服务:

constructor(@Inject(WindowToken) private window: Window, private session: Session)
Run Code Online (Sandbox Code Playgroud)

在您的规范文件中,模拟 window 对象并对其进行测试。我创建了一个带有两个测试服务(一个依赖于另一个)的工作示例。该服务是使用 Angular 的静态注入器创建的:

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

import { CustomHrefService } from './custom-href.service';
import {AppModule} from '../app.module';
import {WindowToken} from './window';
import {Injector} from '@angular/core';
import {CustomHref2Service} from './custom-href-2.service';

const MockWindow = {
  location: {
    _href: '',
    set href(url: string) {
      this._href = url;
    },
    get href() {
      return this._href;
    }
  }
};

describe('CustomHrefService', () => {
  let service: CustomHrefService;
  let setHrefSpy: jasmine.Spy;

  beforeEach(() => {
    setHrefSpy = spyOnProperty(MockWindow.location, 'href', 'set');

    const injector = Injector.create({
      providers: [
        { provide: CustomHrefService, useClass: CustomHrefService, deps: [WindowToken, CustomHref2Service]},
        { provide: CustomHref2Service, useClass: CustomHref2Service, deps: []},
        { provide: WindowToken, useValue: MockWindow}
      ]
    });
    service = injector.get(CustomHrefService);
  });

  it('should be registered on the AppModule', () => {
    service = TestBed.configureTestingModule({ imports: [AppModule] }).get(CustomHrefService);
    expect(service).toEqual(jasmine.any(CustomHrefService));
  });

  describe('#jumpTo', () => {
    it('should modify window.location.href', () => {
      const url = 'http://www.google.com';
      service.jumpTo(url);
      expect(setHrefSpy).toHaveBeenCalledWith(url);
    });
  });
});
Run Code Online (Sandbox Code Playgroud)