1

我正在使用AWS cognitoAmplifyAngular 10

如果用户未登录,我希望不呈现导航栏:

应用程序.html:

<ng-container *ngIf="isLoggedIn">
  <navbar></navbar>
</ng-container>

应用程序.ts:

constructor() {
  this.checkIfLoggedIn();
}

checkIfLoggedIn() {
  Auth.currentUserInfo().then((userData) => {
    if (userData) {
      this.isLoggedIn = true;
    }
  });
}

这行得通。但是,我的单元测试(Karma / Jasmine)会引发错误:

Error: Amplify has not been configured correctly.
        The configuration object is missing required auth properties.

这是因为我不知道如何Auth.currentUserInfo.then正确模拟(尽管阅读了各种关于它的帖子,例如这样那样)。

尝试:

1) 间谍

我以为会是这样的spyOn(Auth, 'currentUserInfo').and.returnValue(Promise.resolve(true));

2)模拟Auth提供者

喜欢评论中的建议。

import { Auth } from 'aws-amplify';

beforeEach(async () => {
  await TestBed.configureTestingModule({
    declarations: [AppComponent],
    providers: [
      {
        provide: Auth,
        useValue: { currentUserInfo: () => Promise.resolve('hello') },
      },
    ],
  }).compileComponents();
}

不幸的是,他们不会让错误消息消失。

4

1 回答 1

1

看起来像是Auth一个全局对象。因此 with 的方式spyOn(Auth, 'currentUserInfo').and.returnValue(Promise.resolve(true));是正确的,但它应该在之前调用TestBed.configureTestingModule

const backup: any;

// faking currentUserInfo
beforeEach(() => {
  backup = Auth.currentUserInfo;
  Auth.currentUserInfo = jasmine.createSpy()
    .and.returnValue(Promise.resolve(true));
});

// restoring original function
afterEach(() => {
  Auth.currentUserInfo = backup;
});

// now our test begins
beforeEach(async () => {
  await TestBed.configureTestingModule({
    declarations: [AppComponent],
  }).compileComponents();
});
于 2020-12-20T17:56:03.630 回答