简体   繁体   English

karma ng-idle 测试失败

[英]karma ng-idle test fails

i've implemented idle-functionality with ng-idle, which works fine.我已经用 ng-idle 实现了空闲功能,效果很好。 i'am trying to implement tests with karma/jasmine but i can not use my idle-service:我正在尝试使用 karma/jasmine 实施测试,但我无法使用我的空闲服务:

UPDATE2更新2

import { Injectable, OnInit, OnDestroy} from '@angular/core';
import { RoutingService } from '../../services/routing/routing.service';
import { Idle, DEFAULT_INTERRUPTSOURCES } from '@ng-idle/core';
import { Keepalive } from '@ng-idle/keepalive';

@Injectable()
export class TimeoutService {

    idleState = 'Not started.';
    timedOut = false;
    lastPing?: Date = null;
    title = 'angular-idle-timeout';
    idleTime = 0;
    timeoutTime = 0;

    constructor(
        public idle: Idle,
        private keepalive: Keepalive,
        public routingService: RoutingService) {
    }

    initIdle(): void {
        this.idle.setIdle(5);
        this.idle.setTimeout(5);
        this.idle.setInterrupts(DEFAULT_INTERRUPTSOURCES);
        this.idle.onIdleEnd.subscribe(() => {
            this.idleState = 'No longer idle.';
            this.reset();
          });

        this.idle.onTimeout.subscribe(() => {
            this.idleState = 'Timed out!';
            this.timedOut = true;     
            this.idle.stop();
            this.timedOut = false;
            this.routingService.navigateToIndex();
        });

        this.idle.onIdleStart.subscribe(() => {
            this.idleState = 'Inaktivität nach 10 Sekunden festgestellt!';

        });

        this.idle.onTimeoutWarning.subscribe((countdown) => {
        this.idleState = 'Buchvorgang wird abgebrochen in ' + countdown + ' Sekunden!';

        });

        this.keepalive.interval(15);
        this.keepalive.onPing.subscribe(() => this.lastPing = new Date());
        this.reset();
    }

    setIdleTime(idleTime): void {
        this.idleTime = idleTime;
    }

    setTimeoutTime(timeoutTime): void {
        this.timeoutTime = timeoutTime;
    }

    getIdleTime(): number {

        return this.idleTime;
    }

    reset() {
        this.idle.watch();
        this.idleState = 'Started.';
        this.timedOut = false;
    }
}

my spec for injectable service我的可注射服务规范

    import { Router } from '@angular/router';
import {async} from '@angular/core/testing';
import { inject, TestBed } from '@angular/core/testing';
import { RoutingService } from '../../services/routing/routing.service';
import { RouterTestingModule } from '@angular/router/testing';
import { TimeoutService } from './timeout.service';
import { Idle, IdleExpiry, DEFAULT_INTERRUPTSOURCES } from '@ng-idle/core';
import { CoreTestingModule } from '../../core-testing.module';
import { Keepalive } from '@ng-idle/keepalive';
import { HttpClient, HttpHandler} from '@angular/common/http';
import { HttpClientTestingModule } from '@angular/common/http/testing';
//import { MockExpiry } from './MockExpiry';

fdescribe('TimeoutService', () => {
    /** let router: Router; */
    let service: TimeoutService;
    let router: Router;
    const mockIdleService = jasmine.createSpyObj('idle', ['initIdle', 'setIdleTime',
                                                            'setTimeoutTime', 'reset',
                                                            'setIdle','setTimeout','setInterrupts',
                                                            'onIdleEnd','onTimeout','onIdleStart',
                                                            'onTimeoutWarning','keepalive','idling']);
    const spies = {
        navigate: null
    };
    jasmine.clock().install();
    beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [HttpClientTestingModule, RouterTestingModule],
            providers: [HttpClient, RoutingService,
                        Keepalive, TimeoutService, Idle, IdleExpiry, { provide: IdleExpiry, useValue: mockIdleService }]
        });
        service = TestBed.get(TimeoutService);
        router = TestBed.get(Router);
        spies.navigate = spyOn(router, 'navigate').and.stub();
    }));

    fit('should navigate to index after 15 Seconds', () => {
        console.log('IDLE TIME VOR DEM INIT-IDLE' + service.idleTime);
        service.initIdle();
        service.setIdleTime(1);
        service.setTimeoutTime(1);
        expect(service.idleTime).toBe( 1 );
        expect(service.timeoutTime).toBe( 1 );
        expect(spies.navigate).toHaveBeenCalledWith(['/index']);

    });
});

Error during test is:测试过程中的错误是:

TypeError: this.expiry.now is not a function at Idle.watch at TimeoutService.reset at TimeoutService.initIdle TypeError: this.expiry.now 不是 TimeoutService.reset at TimeoutService.initIdle 处的 Idle.watch 函数

It seems that TimeoutService relies on Idle .似乎TimeoutService依赖于Idle

You have to mock Idle你必须模拟Idle

import { Router } from '@angular/router';
import { inject, TestBed } from '@angular/core/testing';
import { TimeoutService } from './timeout.service';
import { NgIdleKeepaliveModule } from '@ng-idle/keepalive';

fdescribe('TimeoutService', () => {
    let router: Router;
    const spies = {
        navigate: null
    };

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [RouterTestingModule, NgIdleKeepAliveModule],
            providers: [TimeoutService]
        });
    });


    fit('should navigate to index after 15 Seconds', inject([TimeoutService], (timeoutService: TimeoutService) => {
        // let's assume the idle service has a method idleTime()
        // you can do mockIdleService.idleTime.and.returnValue(10);
        timeoutService.setIdleTime(10);
        timeoutService.setTimeoutTime(5);
        console.log('TEST FINISHED');

    }));
});

Check out Mock Idle in Angular 4 Unit tests .查看Angular 4 单元测试中的模拟空闲 Maybe you can import the whole module itself like Mychal Hackman states.也许您可以像 Mychal Hackman 所说的那样导入整个模块本身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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