【问题标题】:How to mock AWS amplify methods in Angular unit testing如何在 Angular 单元测试中模拟 AWS 放大方法
【发布时间】:2020-12-11 11:32:36
【问题描述】:

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

尝试:

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: () =&gt; 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


【解决方案1】:

看起来Auth 是一个全局对象。 因此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();
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-24
    • 2014-04-16
    • 2021-09-18
    • 1970-01-01
    • 2021-01-27
    • 1970-01-01
    相关资源
    最近更新 更多