Angular 6 - 模拟 authState - 未定义的 valueChanges

Angular 6 - mock authState - valueChanges of undefined

我有一个 属性 和 getter 的服务。 属性 在服务构造函数中设置如下:

public readonly usersMetaData: Observable<User | null>;

constructor(private afAuth: AngularFireAuth,
              private afs: AngularFirestore) {
    this.usersMetaData = this.afAuth.authState.pipe(switchMap((user: firebase.User) => {
        if (user) {
            return this.afs.doc<User>(`users/${user.uid}`).valueChanges();
        } else {
            return of(null);
        }
    }), share());
}

我的 getter 只是测试 authstate returns 基本上是一个已定义的对象(不是 null,不是未定义的):

public isAuthenticated(): Observable<boolean> {
    return this.usersMetaData.pipe(map(user => !!user));
}

现在对于我的单元测试设置,我需要从 firebase 模拟 authState。看起来如下:

  let service: AuthService;

  const authStub: any = {
    authState: {}
  };

  const storeStub = {
    doc() {
      return of(null);
    }
  };

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        {provide: AngularFireAuth, useValue: authStub},
        {provide: AngularFirestore, useValue: storeStub},
        AuthService
      ]
    });

    authStub.authState = of({username: 'test'});
    spyOn(storeStub, 'doc').and.stub();
    service = TestBed.get(AuthService);
  });

  it('should check for authentication - is authenticated', async(() => {
    service.isAuthenticated().subscribe(isUser => console.log(isUser)); <== should return true
  }));

返回的错误是:Failed: Cannot read property 'valueChanges' of undefined 有谁知道如何正确模拟 authstate?

差不多吧。 storeStub obj 需要这样修改:

  const storeStub = {
    doc() {
      return {
        valueChanges() {
          return of({property: 'test'});
        }
      };
    }
  };

由于 doc 调用了 valueChanges,因此您需要 return 模拟对象中的 valueChanges。

如果您碰巧是发现此页面的 Jest 用户,请尝试:

const storeStub = {
    collection: jest.fn(),
    doc: jest.fn().mockImplementation(() => ({
        valueChanges: jest
            .fn()
            .mockImplementation(() => of(mockUserProfile)),
    })),
};