网站搜索

angular - 无法使用 bindNodeCallback


我正在尝试这个:

return Observable.bindNodeCallback(this.webAuth.client.userInfo)(this.accessToken);

我正在尝试从 Auth0 的 userInfo 函数创建一个可观察对象,以便我可以在 AuthGuard 中的 canActivate 使用它。

但是我遇到了这个错误:

TS2346:Supplied parameters do not match any signature of call target.

上面的库函数是:

Authentication.prototype.userInfo = function(accessToken, cb) {
  var url;
  assert.check(accessToken, {
    type: 'string',
    message: 'accessToken parameter is not valid'
  });
  assert.check(cb, {
    type: 'function',
    message: 'cb parameter is not valid'
  });
  url = urljoin(this.baseOptions.rootUrl, 'userinfo');
  return this.request
    .get(url)
    .set('Authorization', 'Bearer ' + accessToken)
    .end(responseHandler(cb, {
      ignoreCasing: true
    }));
};

答案#1

我遇到了完全相同的问题。最终,我没有使用bindNodeCallback(),而是发现你可以直接将整个对userInfo()的调用包装在Observable.create()中,像这样(注意:外部的userInfo()函数是我AuthProvider类的一部分):

userInfo = (token: string): Observable<User> => Observable.create(observer => {
  this.auth0.client.userInfo(token, (err: any, user: User) => {
    if (err) {
      observer.error(err);
    }
    observer.next(user);
    observer.complete();
  });
});

使用 Jest 进行测试

如果你想为上面的代码编写单元测试,我使用了由 @cartant 开发的出色 rxjs-marbles 库(他在上面的评论中有回应)。以下是我测试相关部分的一些片段:

import { TestBed } from '@angular/core/testing';
import { marbles } from 'rxjs-marbles/jest'; // <-- add /jest here to level-up!
import { Observable } from 'rxjs';
import { StoreModule, Store } from '@ngrx/store';
import { AuthProvider } from './auth'; // my authentication service

// Here's a mock for the relevant bits of the Auth0 library
jest.mock('auth0-js', () => ({
  WebAuth: options => ({
    client: {
      userInfo: (token, cb) => { 
        if ( "error" === token ) {
          cb(new Error("Profile error!"), null);
        } else {
          cb(null, {name: "Alice"}); 
        }
      }
    }
  })
}));

describe("Auth0.WebAuth.client", () => {
  let auth: AuthProvider;
  let store: Store<any>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports:   [ StoreModule.forRoot({}) ],
      providers: [ AuthProvider ]
    });
    store = TestBed.get(Store);
    spyOn(store, 'pipe');
    auth = TestBed.get(AuthProvider);
  });

  it("should return Observable<User> when calling userInfo()", marbles((m) => {
    const user = { name: "Alice" }; // must match mocked value above
    const source = m.cold("--a", { a: "dummy-access-token" });
    const target = m.cold("--b", { b: user });
    const profile = source.flatMap(auth.userInfo);

    m.expect(profile).toBeObservable(target);
 }));

  it("throw Error on fail when calling userInfo()", marbles((m) => {
    const err = new Error("Profile error!"); // must match mocked value above
    const source = m.cold("--a", { a: "error" }); // this value triggers mock error
    const target = m.cold("--#", null, err);
    const profile = source.flatMap(auth.userInfo);

    m.expect(profile).toBeObservable(target);
  }));
});

我遇到的一些陷阱:

  • 确保在测试中使用 flatMap()!我为此卡住了很久
  • 我对大理石测试很陌生,我必须多次阅读手册,才真正掌握其中的内容

答案#2

我知道这是一个旧帖,但我已经能够让我的 auth0 userInfo 方法使用 bindNodeCallback。

如果对有人有帮助,这是我的解决方案:

// must use the bind() method to change scope of "this" inside the userInfo function
private _userInfo$ = bindNodeCallback(this._Auth0.client.userInfo.bind(this._Auth0.client));

// Get user information
public getUserInfo$() : Observable<any>{

  return this.token$.pipe(
    switchMap(token => this._userInfo$(token))
  );

}

// Check if users email is verified
public checkEmailVerified$() : Observable<boolean>{

  return this.token$.pipe(
    switchMap(token => this._userInfo$(token)),
    map(userInfo => userInfo.email_verified )
  );

}