[英]How to mock AWS amplify methods in Angular unit testing
我正在使用AWS cognito 、 Amplify和Angular 10 。
如果用戶未登錄,我希望不呈現導航欄:
app.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
(盡管閱讀了各種關於它的帖子,例如this或that )。
嘗試:
1) 間諜
我認為它會像spyOn(Auth, 'currentUserInfo').and.returnValue(Promise.resolve(true));
2) Mocking 在提供程序中進行身份Auth
喜歡評論中的建議。
import { Auth } from 'aws-amplify';
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [AppComponent],
providers: [
{
provide: Auth,
useValue: { currentUserInfo: () => Promise.resolve('hello') },
},
],
}).compileComponents();
}
不幸的是,他們沒有發出錯誤消息 go 。
看起來Auth
是一個全局 object。 因此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();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.