【发布时间】:2020-12-11 11:32:36
【问题描述】:
我正在使用AWS cognito、Amplify 和Angular 10。
如果用户未登录,我希望不呈现导航栏:
app.html:
<ng-container *ngIf="isLoggedIn">
<navbar></navbar>
</ng-container>
app.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(尽管阅读了各种关于它的帖子,例如 this 或 that)。
尝试:
1) 间谍
我认为它会像spyOn(Auth, 'currentUserInfo').and.returnValue(Promise.resolve(true));
2) 在提供者中模拟 Auth
喜欢comments中的建议。
import { Auth } from 'aws-amplify';
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [AppComponent],
providers: [
{
provide: Auth,
useValue: { currentUserInfo: () => Promise.resolve('hello') },
},
],
}).compileComponents();
}
不幸的是,他们没有让错误消息消失。
【问题讨论】:
-
Auth 已初始化,即使您已对其进行了监视。试用提供者
{provide: Auth, useValue: { currentUserInfo: () => Promise.resolve(true) }} -
非常感谢您的帮助,非常感谢。不幸的是,这不起作用,我相应地更新了我的问题。
-
你试过用
useClass: MyClass代替useValue吗? -
是的。这会产生“无法访问”的错误,如下所述:stackoverflow.com/questions/62281756/…
-
好吧,用错了。如果我模拟一个服务(请参阅stackoverflow.com/a/62284218/3255061),没有“无法访问”,但仍然存在“错误:未正确配置 Amplify。配置对象缺少必需的身份验证属性。”错误。
标签: angular unit-testing karma-runner aws-amplify aws-amplify-sdk-js