如何使用依赖项对功能进行单元测试(角度)

时间:2019-05-24 14:28:38

标签: javascript angular unit-testing karma-jasmine oidc-client-js

我是单元测试的新手,并且掌握了一些基础知识。但是,我正在尝试测试一种方法。此方法调用一个函数,该函数是oidc-client.js的一部分。它基本上可以使用户登录。

  

规格文件


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

import { AuthCallbackComponent } from './auth-callback.component';
import { RouterTestingModule } from '@angular/router/testing';


fdescribe('AuthCallbackComponent', () => {
  let component: AuthCallbackComponent;
  let fixture: ComponentFixture<AuthCallbackComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule],
      declarations: [ AuthCallbackComponent ]
    })
    .compileComponents();
  }));

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

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

  

component.ts

import { UserManager,User,UserManagerSettings,WebStorageStateStore} from 'oidc-client';

  manager = new UserManager(this.getClientSettings());


  ngOnInit() {
    this.authService.completeAuthentication();

  }


  completeAuthentication(): Promise<void> {
    return this.manager.signinRedirectCallback().then(user => {
      this.user = user;
      this.router.navigate(['/']);
      this.setUser.next(this.user.profile);
      this.onLogin.next(true)
    });
  }



  getClientSettings() {
    return {
      authority: environment.authority,
      client_id: environment.client_id,
      redirect_uri: environment.login,
      post_logout_redirect_uri: environment.logout,
      response_type: 'code',
      scope: 'openid profile email phone address',
      filterProtocolClaims: true,
      loadUserInfo: false,
      accessTokenExpiringNotificationTime: 60,
      silentRequestTimeout: 10000,
      includeIdTokenInSilentRenew: true,
      automaticSilentRenew: true,
      silent_redirect_uri: environment.silent_redirect
    };
  }
}

我不确定如何进行测试。当我运行测试时,我得到的是“无状态响应”。我希望测试通过,也许还想知道如何测试completeAuthentication()

1 个答案:

答案 0 :(得分:0)

Sinon's stub object是测试您无法控制的代码的一种工具,它可以让您模拟所需的第三方依赖行为。

在没有看到您要测试的源代码的情况下,没有太多余地,但是我希望Sinon项目中的示例文档足以满足您的用例。

相关问题