我遇到了完全相同的问题。最终,我不再使用bindNodeCallback(),而是像这样使用discovered you can just wrap the entire call to userInfo() in 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 library(他在上面的 cmets 中做出了回应)。以下是我测试相关部分的一些 sn-ps:
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);
}));
});
我遇到的一些陷阱: