簡體   English   中英

在 Angular 4 單元測試中模擬空閑

[英]Mock Idle in Angular 4 Unit tests

在此之后,我嘗試使用 karma 為 Angular4 應用程序編寫單元測試我在TestBed.createComponent(ServicesComponent)處收到錯誤,因此沒有執行任何測試用例,並且

TypeError: this.expiry.last is not a function at Idle.Array.concat.Idle.watch...

在構造函數中編寫了很多東西(其中進行了服務調用並編寫了空閑功能),應該如何為此編寫測試用例?

這是我的規范文件,在組件的構造函數中使用了空閑函數,我必須添加IdleExpiryKeepalive提供程序,以免出現Error: No provider for IdleExpiry

beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [                    
                ServicesComponent
            ],
            providers: [
                { provide: ServicesService, useClass: ServicesService },
                { provide: LocalStorageService, useClass: MockLocalStorageService },
                { provide: ServiceUtilities, useClass: ServiceUtilities },
                { provide: Idle, useClass: Idle },
                { provide: IdleExpiry, useClass: IdleExpiry },
                { provide: Keepalive, useClass: Keepalive },
                { provide: Router, useValue: routerStub },
                { provide: ActivatedRoute, useValue: activatedrouteStub },
                MockBackend,
                BaseRequestOptions,
                {
                    provide: Http,
                    useFactory: (backend, options) => new Http(backend, options),
                    deps: [MockBackend, BaseRequestOptions]
                }
            ],
            imports: [
                ModalModule.forRoot()
            ]
        }).compileComponents();
    }));
beforeEach(() => {            
        fixture = TestBed.createComponent(ServicesComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

組件(不包括不必要的細節(替換為...))

export class ServicesComponent {
    ...
    approxWaitingTime: string;
    idleState = 'Not started.';
  timedOut = false;
  lastPing?: Date = null;
@ViewChild('autoShownModal') public autoShownModal: ModalDirective;
public isModalShown:boolean = false;
timer: any;
constructor(private servicesService: ServicesService, private route: ActivatedRoute, private router: Router, private idle: Idle, private keepalive: Keepalive) {

    this.servicesService.getServices(this.centerId).subscribe(data => { ... });
    this.servicesService.getCategories(this.centerId).subscribe(data => {  ... });
    this.servicesService.getStylists(this.centerId).subscribe(data => { ... });
    this.servicesService.getApproxWaitingTime(this.centerId).subscribe(data => { ... });

    this.route.queryParams.subscribe(params => { ... });

    // sets an idle timeout of 120 seconds, for testing purposes.
    idle.setIdle(10);
    // sets a timeout period of 30 seconds. after 30 seconds of inactivity, the user will be considered timed out.
    idle.setTimeout(5);
    // sets the default interrupts, in this case, things like clicks, scrolls, touches to the document
    idle.setInterrupts(DEFAULT_INTERRUPTSOURCES);

    idle.onIdleEnd.subscribe(() => this.idleState = 'No longer idle.');
    idle.onTimeout.subscribe(() => {
        console.log("ontimeout");
        this.idleState = 'Timed out!';
        this.timedOut = true;
    });
    idle.onIdleStart.subscribe(() => this.idleState = 'You\'ve gone idle!');
    idle.onTimeoutWarning.subscribe((countdown, router, autoShownModal) => {
        console.log("time out" + countdown);
        this.isModalShown = true;
        this.timer = setTimeout(function () { if (this.isModalShown) { this.hideModal(); } this.reset(); this.router.navigate(['']); }.bind(this), 3000);
        this.reset();
    });

    // sets the ping interval to 15 seconds
    keepalive.interval(10);

    keepalive.onPing.subscribe(() => { this.lastPing = new Date(); console.log('Keepalive.ping() called!'); });

    this.reset();
}
...

我缺什么嗎?

這是我為使組件加載所做的工作,Mocked IdleExpiry

export class MockExpiry extends IdleExpiry {
  public lastDate: Date;
  public mockNow: Date;

  last(value?: Date): Date {
    if (value !== void 0) {
      this.lastDate = value;
    }

    return this.lastDate;
  }

  now(): Date {
    return this.mockNow || new Date();
  }
}

更新了規范

providers: [
...
    { provide: IdleExpiry, useClass: MockExpiry },
...
],

正確的解決方案是將NgIdleKeepaliveModule添加到NgIdleKeepaliveModuleimports中。

我還建議不要在模擬中擴展您正在模擬的類(然而,實現並不是一個壞主意)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM