Карма нг-холостого теста не проходит - PullRequest
0 голосов
/ 26 февраля 2020

Я реализовал idle-функциональность с помощью ng-idle, которая отлично работает. я пытаюсь реализовать тесты с кармой / жасмином, но я не могу использовать свой бездействующий сервис:

ОБНОВЛЕНИЕ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;
    }
}

мой показатель c для инъекций 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']);

    });
});

Ошибка во время теста:

TypeError: this.expiry.now не является функцией в Idle.watch в TimeoutService.reset в TimeoutService.initIdle

1 Ответ

1 голос
/ 27 февраля 2020

Похоже, что TimeoutService полагается на 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');

    }));
});

Выезд Макет холостого хода в Angular 4 юнит Тесты . Может быть, вы можете импортировать весь модуль, как утверждает Мичал Хэкман.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...