繁体   English   中英

如何在 Angular 单元测试中模拟 AWS 放大方法

[英]How to mock AWS amplify methods in Angular unit testing

我正在使用AWS cognitoAmplifyAngular 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 (尽管阅读了各种关于它的帖子,例如thisthat )。

尝试:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM