如何使用 then 块对返回 Promise 的函数进行单元测试

发布于 2025-01-20 18:36:22 字数 2319 浏览 3 评论 0原文

我有这段代码来使用 OAuth2 初始化身份验证,并在访问我的应用程序之前将用户重定向到身份验证服务器

import {Component} from '@angular/core';
import {JwksValidationHandler, OAuthService} from 'angular-oauth2-oidc';
import {authConfig} from './sso.config';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})

export class AppComponent {

  constructor(private oauthService: OAuthService) {}

  async initAuth(): Promise<any> {
    return new Promise<void>((resolveFn, rejectFn) => {
      this.oauthService.configure(authConfig);
      this.oauthService.tokenValidationHandler = new JwksValidationHandler();
      this.oauthService.loadDiscoveryDocumentAndTryLogin().then(() => {
        if (this.oauthService.hasValidAccessToken()) {   // ----------------> My test can't get in this part
          this.oauthService.setupAutomaticSilentRefresh();
          resolveFn();
        }else {
          this.oauthService.initCodeFlow();
          rejectFn();
        }
      });// --------------------------------> It goes directly here and gives me: SPEC HAS NO EXPECTATIONS
    });
  }

}

我想使用 Jasmine 和 Karma 对这部分进行单元测试,我的测试如下所示:

describe('AppComponent', () => {
  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;

  const oauthServiceMock = {
    oauthService: {
      loadDiscoveryDocumentAndTryLogin(): Promise<true> {
        return new Promise<true>(resolve => resolve());
      }
    }
  };

  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      imports: [OAuthModule.forRoot(), HttpClientTestingModule],
      providers: [
       {provide: AppComponent, useValue: oauthServiceMock}
      ],
      declarations: [
        AppComponent
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    }).compileComponents();

    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

  }));

  it('Test for initAuth', fakeAsync(() => {

    const spy = spyOn(oauthServiceMock.oauthService, 'loadDiscoveryDocumentAndTryLogin').and.returnValue(Promise.resolve(true));

    component.initAuth().then(() => {
      tick(5000);
      expect(spy).toHaveBeenCalled();

    });

  }));

});

我的测试无法进入块然后我不知道我错过了什么。

I have this code to initialize an authentication using OAuth2 and redirect the user to an authentication server before getting to my application

import {Component} from '@angular/core';
import {JwksValidationHandler, OAuthService} from 'angular-oauth2-oidc';
import {authConfig} from './sso.config';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})

export class AppComponent {

  constructor(private oauthService: OAuthService) {}

  async initAuth(): Promise<any> {
    return new Promise<void>((resolveFn, rejectFn) => {
      this.oauthService.configure(authConfig);
      this.oauthService.tokenValidationHandler = new JwksValidationHandler();
      this.oauthService.loadDiscoveryDocumentAndTryLogin().then(() => {
        if (this.oauthService.hasValidAccessToken()) {   // ----------------> My test can't get in this part
          this.oauthService.setupAutomaticSilentRefresh();
          resolveFn();
        }else {
          this.oauthService.initCodeFlow();
          rejectFn();
        }
      });// --------------------------------> It goes directly here and gives me: SPEC HAS NO EXPECTATIONS
    });
  }

}

I would like to unit test this part using Jasmine and Karma, my test looks like:

describe('AppComponent', () => {
  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;

  const oauthServiceMock = {
    oauthService: {
      loadDiscoveryDocumentAndTryLogin(): Promise<true> {
        return new Promise<true>(resolve => resolve());
      }
    }
  };

  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      imports: [OAuthModule.forRoot(), HttpClientTestingModule],
      providers: [
       {provide: AppComponent, useValue: oauthServiceMock}
      ],
      declarations: [
        AppComponent
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    }).compileComponents();

    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

  }));

  it('Test for initAuth', fakeAsync(() => {

    const spy = spyOn(oauthServiceMock.oauthService, 'loadDiscoveryDocumentAndTryLogin').and.returnValue(Promise.resolve(true));

    component.initAuth().then(() => {
      tick(5000);
      expect(spy).toHaveBeenCalled();

    });

  }));

});

My test can't get into the block then I don't know what am I missing.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

倾城月光淡如水﹏ 2025-01-27 18:36:22

我认为您错误地提供了模拟函数。

更改为:

const oauthServiceMock = {
    oauthService: {
      loadDiscoveryDocumentAndTryLogin(): Promise<true> {
        return new Promise<true>(resolve => resolve());
      }
    }
  };

更改

    oauthService: {
      loadDiscoveryDocumentAndTryLogin(): Promise<true> {
        return new Promise<true>(resolve => resolve());
      }
    }

为: 更改

providers: [
       {provide: AppComponent, useValue: oauthServiceMock}
      ],

为:

providers: [
       {provide: OAuthService, useValue: oauthServiceMock}
      ],

我们需要为 OAuthService 而不是 AppComponent 提供模拟。这应该有望解决您的问题。

I think you're providing the mock function incorrectly.

Change this:

const oauthServiceMock = {
    oauthService: {
      loadDiscoveryDocumentAndTryLogin(): Promise<true> {
        return new Promise<true>(resolve => resolve());
      }
    }
  };

To this:

    oauthService: {
      loadDiscoveryDocumentAndTryLogin(): Promise<true> {
        return new Promise<true>(resolve => resolve());
      }
    }

And change this:

providers: [
       {provide: AppComponent, useValue: oauthServiceMock}
      ],

To this:

providers: [
       {provide: OAuthService, useValue: oauthServiceMock}
      ],

We need to provide a mock to OAuthService and not AppComponent. That should hopefully resolve your issue.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文