Angular 6测试路由重定向

时间:2019-05-23 09:14:05

标签: angular typescript karma-jasmine

我必须测试注销功能:

logout() {
  this.deleteSession();
  this.router.navigate(['login']);
}

然后我在component.spec.ts

中进行了此测试
describe('AuthService', () => {
  let location: Location;
  let router: Router;
  let httpTestingController: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [MessageService, JwtHelperService, Location],
      imports: [HttpClientTestingModule, RouterTestingModule, JwtModule.forRoot({
        config: {
          tokenGetter: () => {
            return sessionStorage.getItem(environment.tokenName);
          },
          //Exclude this URL from JWT (doesn't add the authentication header)
          blacklistedRoutes: [
            '/api/login',
          ]
        }
      }),]
    });

    router = TestBed.get(Router);
    location = TestBed.get(Location);
    // Inject the http service and test controller for each test
    httpTestingController = TestBed.get(HttpTestingController);
    router.initialNavigation();
  });

  afterEach(() => {
    // After every test, assert that there are no more pending requests.
    httpTestingController.verify();
  });

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

  it('#saveToken should be saved the token into local storage', () => {
    const authService: AuthService = TestBed.get(AuthService);
    authService.saveToken('1234');
    expect(sessionStorage.getItem(environment.tokenName)).toBe('1234', 'token is not saved');
  });

  it('#getSessionToken should be retrieved the token from local storage', () => {
    const authService: AuthService = TestBed.get(AuthService);
    expect(authService.getSessionToken).toBe(sessionStorage.getItem(environment.tokenName), 'token is not retrieved');
  });

  it('#deleteSession should be deleted the token from local storage', () => {
    const authService: AuthService = TestBed.get(AuthService);
    authService.deleteSession();
    expect(authService.getSessionToken).toBe(null, 'token is not deleted');
  });

  it('#login should be logged the user', () => {
    const authService: AuthService = TestBed.get(AuthService);
    let username = "test";
    let password = "test"
    // We call the service
    authService.login(username, password).subscribe(data => {
      expect(data.valid).toBe(true);
      expect(data.token).not.toBeNull();
    });

    // We set the expectations for the HttpClient mock
    const req = httpTestingController.expectOne((request: HttpRequest<any>) => {
      return request.method == 'POST'
        && request.url == '/api/login'
        && JSON.stringify(request.body) == JSON.stringify({
          username, password
        })
        && request.headers.get('Content-Type') === 'application/json';
    });

    let sessionTokenResponse:  SessionTokenResponse = { token:"dsadsad.dsadsghfg.gfcdcv", valid:true, reason:''};
    req.flush(sessionTokenResponse);
    expect(req.request.method).toEqual('POST');
    // Finally, assert that there are no outstanding requests.
    httpTestingController.verify();
  });

  it('#decodeToken should be decoded the token', () => {
    const authService: AuthService = TestBed.get(AuthService);
    let testToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsInVzZXJuYW1lIjoidGVzdCIsImlhdCI6MTU1ODU5NDAwMSwicm9sZSI6IkFETUlOIn0.MxbWHIBAluZYPpeslJxYWWl71jv97HWPPdTWynsZay0";
    authService.saveToken(testToken);
    expect(authService.decodeToken.username).toBe('test', 'username is not test');
  });


  it('#logout should be made the logout', fakeAsync(() => {
    const authService: AuthService = TestBed.get(AuthService);
    authService.logout();
    tick();
    expect(authService.getSessionToken).toBe(null, 'token is not deleted');
    expect(location.path()).toBe('login');
  }));


});

错误位于expect(location.path()).toBe('login');上,是“”而不是“登录”

Expected '' to be 'login'.

如何解决此错误?谢谢

0 个答案:

没有答案