简体   繁体   中英

How to unit test a function with a dependency (angular)

I'm new to unit testing and have some got basics down. However, I'm trying to test a method. This method calls a function which is part of the oidc-client.js. It basically signs a user in.

spec file


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
    };
  }
}

I'm not sure how I go about testing this. When I run the test I have I just get ' No state in response'. I want the test to pass and maybe some ideas on how to test the completeAuthentication()

One tool for testing code you have no control over is Sinon's stub object , which can allow you to mock out the desired behavior of the 3rd party dependency.

There isn't much to go off of in the question without seeing the source code you are trying to test, but I hope the example documentation in the Sinon project will be sufficient for your use case.

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