StaticInjectorError Spec角度测试

时间:2019-03-28 15:10:18

标签: angular angular-test angular-testing

通常,如果我未在Testbed中包括依赖项,则会收到以下错误,这是我正在测试的类的构造函数所必需的。但是在这种情况下,缺少的依赖关系就是我正在测试的类。

错误

Error: StaticInjectorError[AuthGuardService]: 
      NullInjectorError: No provider for AuthGuardService!

问题:

我需要添加什么才能通过测试?

AuthGuardService规范

import {TestBed} from '@angular/core/testing';
import {AuthGuardService} from './auth-guard.service';
import {UserService} from '../user/user.service';
import {Router} from '@angular/router';
import {RouterTestingModule} from '@angular/router/testing';

describe('AuthGuardService', () => {
  beforeEach(() => {
    const userServiceSpy = jasmine.createSpyObj('UserService', ['isAuthenticated']);
    const routerServiceSpy = jasmine.createSpyObj('RouterService', ['navigate']);
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      providers: [
        {provide: UserService, useValue: userServiceSpy},
        {provide: Router, useValue: routerServiceSpy}
      ]
    });
  });

  it('should be created', () => {
    const service: AuthGuardService = TestBed.get(AuthGuardService);
    expect(service).toBeTruthy();
  });
});

AuthGuardService

import {Injectable} from '@angular/core';
import {Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router';
import {UserService} from '../user/user.service';

@Injectable()
export class AuthGuardService implements CanActivate {
  constructor(private userService: UserService, private router: Router) {
  }

  async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    const authStatus = await this.userService.isAuthenticated();
    if (authStatus === true) {
      return true;
    }
    this.router.navigate(['front'], {queryParams: {returnUrl: state.url}});
    return false;
  }
}

0 个答案:

没有答案