Жасмин юнит тестирование в Стамбуле - PullRequest
0 голосов
/ 27 января 2019

Я делаю юнит-тестирование с Жасмин и Стамбулом.

Я пытаюсь провести юнит-тестирование по следующему методу:

 getDiploma(spinnerMessage: string): Observable<DiplomaModel> {
        const diploma = this.diplomasState.diploma;
        if (diploma) {
            // Return diploma info from store
            return observableOf(diploma);
        } else {
            // Get and return diploma info from backend
            return this.http.get<DiplomaModel>(this.apiDiploma, spinnerMessage).pipe(map((result) => {
                return this.setDiplomasInStore(result);
            }));
        }
    }

И мой юнит-тест выглядит так:

 it('It should return diploma from the backend when snapshot exist ', () => {

            diplomaStoreServiceMock.returnState(Object.assign({}, this.diplomaState));
            const diplomaState = diplomaService.getDiplomaSnapshot();
            expect(diplomaState).toEqual(Object.assign({}, this.diplomaState));

            // tslint:disable-next-line:no-commented-code
            /*  const response = [{ mock: 'mock' } as any];
             diplomaService['getDiplomaSnapshot'] = response;
             diplomaService.getDiplomaState().subscribe(i => {
                 expect(i).toEqual(response);
             }); */
        });

it('It should return diploma if snapshot doenst exist', () => {
    const apiString = 'api/register/teachers/current/diploma';
    const spyHttp = spyOn(afwHttp, 'get').and.callThrough();
    const spyDocument = spyOn(diplomaService, 'getDiploma').and.callThrough();

    diplomaStoreServiceMock.returnState({});
    const response = { 'mock': 'mockResult' };
    afwHttp.setupOnlyResponse(response, 200);
    diplomaService.getDiploma('spinnerText').subscribe(result => expect(result['mock']).toEqual('mockResult'));
    afwHttp.returnOnlyResponse();
    expect(spyHttp).toHaveBeenCalledWith(apiString, 'spinnerText');
    expect(spyDocument).toHaveBeenCalledWith('spinnerText');
});

Но в Стамбуле у меня по-прежнему красная линия на этой строке:

 return observableOf(diploma);

со знаком I, и если я наведу курсор на I, то будет:

, если путь не указанпринято.

Итак, как решить эту проблему?

Спасибо.

но вот почему у меня есть два метода.Но вы имеете в виду этот метод:

it('It should return diploma from the backend when snapshot exist ', () => {



     diplomaStoreServiceMock.returnState(Object.assign({}, this.diplomaState));
        const diplomaState = diplomaService.getDiplomaSnapshot();
        expect(diplomaState).toEqual(Object.assign({}, this.diplomaState));
    });

Что я должен изменить в этом методе теста?

Вы имеете в виду так:

 it('It should return diploma from the backend when snapshot exist ', () => {

        diplomaStoreServiceMock.returnState(Object.assign({}, this.diplomaState));
        const diplomaState = diplomaService.getDiplomaSnapshot();
        diplomaService.getDiploma('spinnerText');
        expect(diplomaState).toEqual(Object.assign({}, this.diplomaState));
    });

Я тоже пытался так:

it('It should return diploma from the backend when snapshot exist ', () => {
    const response = [{ mock: 'mock' } as any];
    diplomaStoreServiceMock.returnState(Object.assign({}, this.diplomaState));
    const diplomaState = diplomaService.getDiplomaSnapshot();
    diplomaService.getDiploma('spinnerText').subscribe( i => {
        expect(i).toEqual(response);

    });
    expect(diplomaState).toEqual(Object.assign({}, this.diplomaState));
});

И если я добавлю этот метод:

  it('It should return diploma', () => {
        const response = [{ mock: 'mock' } as any];
        diplomaService.getDiploma('spinnerText').subscribe( i => {
            expect(i).toEqual(response);

        });
    });

Я получу эту ошибку:

ОШИБКА в apps / register / src / app /shared / services / src / diploma.service.spec.ts (67,31): ошибка TS2345: Аргумент типа 'any []' не может быть назначен параметру типа 'Expected'.Тип 'any []' нельзя назначить типу 'ObjectContained'.Свойство 'jasmineMatches' отсутствует в типе 'any []'.

Теперь у меня есть три метода:

 it('It should return diploma from the backend when snapshot exist ', () => {
        diplomaStoreServiceMock.returnState(Object.assign({}, this.diplomaState));
        const diplomaState = diplomaService.getDiplomaSnapshot();
        expect(diplomaState).toEqual(Object.assign({}, this.diplomaState));
    });

    it('It should return diploma', () => {
        const response = [{ mock: 'mock' } as any];
        diplomaService.getDiploma('spinnerText').subscribe( i => {
            expect(i).toEqual(response);

        });
    });


    it('It should return diploma if snapshot doenst exist', () => {
        const apiString = 'api/register/teachers/current/diploma';
        const spyHttp = spyOn(afwHttp, 'get').and.callThrough();
        const spyDocument = spyOn(diplomaService, 'getDiploma').and.callThrough();
        const response = { 'mock': 'mockResult' };
        afwHttp.setupOnlyResponse(response, 200);
        diplomaService.getDiploma('spinnerText').subscribe(result => expect(result['mock']).toEqual('mockResult'));
        afwHttp.returnOnlyResponse();
        expect(spyHttp).toHaveBeenCalledWith(apiString, 'spinnerText');
        expect(spyDocument).toHaveBeenCalledWith('spinnerText');
    });

Это файл теста отверстия:

describe('Services: DiplomaService', () => {


    let afwHttp: AfwHttpMock;
    let diplomaService: DiplomaService;
    let diplomaStoreServiceMock: DiplomaStoreServiceMock;
    let feedbackStoreServiceMock: FeedbackStoreServiceMock;
    let multiFileUploadServiceMock: MultiFileUploadServiceMock;




    beforeEach(() => {
        afwHttp = new AfwHttpMock();
        diplomaStoreServiceMock = new DiplomaStoreServiceMock();
        multiFileUploadServiceMock = new MultiFileUploadServiceMock();
        feedbackStoreServiceMock = new FeedbackStoreServiceMock();
        diplomaService = new DiplomaService(afwHttp as any,
            diplomaStoreServiceMock as any,
            feedbackStoreServiceMock as any,
            multiFileUploadServiceMock as any);
    });

    it('should create an instance', () => {
        expect(diplomaService).toBeTruthy();
    });


    it('It should return diplomadocumentList', () => {
        // tslint:disable-next-line:no-duplicate-string
        const apiString = 'api/register/teachers/current/diploma';
        const spyHttp = spyOn(afwHttp, 'get').and.callThrough();
        const spyDocumentList = spyOn(diplomaService, 'getDiplomaDocumentList').and.callThrough();
        const response = { 'mock': 'mockResult' };
        afwHttp.setupOnlyResponse(response, 200);

        const result2 = diplomaService.getDiplomaDocumentList('spinnerText');
        result2.subscribe(() => {
            expect(spyHttp).toHaveBeenCalledWith(apiString, 'spinnerText');
            expect(spyDocumentList).toHaveBeenCalledWith('spinnerText');
        });
        afwHttp.returnOnlyResponse();
    });


    // tslint:disable-next-line:no-commented-code

    it('It should return diploma from the backend when snapshot exist ', () => {
        diplomaStoreServiceMock.returnState(Object.assign({}, this.diplomaState));
        const diplomaState = diplomaService.getDiplomaSnapshot();

        diplomaService.getDiploma('spinnerText').subscribe(result => expect(result['mock']).toEqual('mockResult'));

        expect(diplomaState).toEqual(Object.assign({}, this.diplomaState));
    });

   // tslint:disable-next-line:no-commented-code
   /*  it('It should return diploma', () => {
        const response = [{ mock: 'mock' } as any];
        diplomaService.getDiploma('spinnerText').subscribe( i => {
            expect(i).toEqual(response);

        });
    }); */


    it('It should return diploma if snapshot doenst exist', () => {
        const apiString = 'api/register/teachers/current/diploma';
        const spyHttp = spyOn(afwHttp, 'get').and.callThrough();
        const spyDocument = spyOn(diplomaService, 'getDiploma').and.callThrough();
        const response = { 'mock': 'mockResult' };
        afwHttp.setupOnlyResponse(response, 200);
        diplomaService.getDiploma('spinnerText').subscribe(result => expect(result['mock']).toEqual('mockResult'));
        afwHttp.returnOnlyResponse();
        expect(spyHttp).toHaveBeenCalledWith(apiString, 'spinnerText');
        expect(spyDocument).toHaveBeenCalledWith('spinnerText');
    });

    // tslint:disable-next-line:no-identical-functions
    it('It should save diploma record to database', () => {

        const apiString = 'api/register/teachers/current/diploma';
        const spyHttp = spyOn(afwHttp, 'post').and.callThrough();
        const spyDocument = spyOn(diplomaService, 'saveDiplomaMetaData').and.callThrough();
        const response = { 'mock': 'mockResult' };
        afwHttp.setupOnlyResponse(response, 200);

        const result2 = diplomaService.saveDiplomaMetaData(false, 'spinnerText');
        result2.subscribe(() => {
            expect(spyHttp).toHaveBeenCalledWith(apiString, 'spinnerText');
            // tslint:disable-next-line:no-commented-code
            expect(spyDocument).toHaveBeenCalledWith(false, 'spinnerText');
        });
        afwHttp.returnOnlyResponse();
    });

    it('It should save documents for  diploma record', fakeAsync(() => {
        const spy = spyOn(multiFileUploadServiceMock, 'syncFilesWithBackend').and.callThrough();
        const spyFeedback = spyOn(feedbackStoreServiceMock, 'addErrorMessage');

        multiFileUploadServiceMock.setResponse([{ error: 'error' }]);


        diplomaService.saveDocumentForDiploma([{} as any], () => { }, MultiFileUploadResourcesModel.keys, { key: 'diploma', value: 'document' });

        expect(spy).toHaveBeenCalledWith('api/register/teachers/current/diploma/documents', [{}],
            MultiFileUploadResourcesModel.keys.bijlageToevoegenSpinnerTekst,
            MultiFileUploadResourcesModel.keys.bijlageVerwijderenSpinnerTekst
        );

        tick();
        expect(spyFeedback).toHaveBeenCalled();
    }));

    // tslint:disable-next-line:no-identical-functions
    it('should return document list ', fakeAsync(() => {
        const apiString = 'api/register/teachers/current/diploma';
        const spyHttp = spyOn(afwHttp, 'get').and.callThrough();
        const spyDocumentList = spyOn(diplomaService, 'getDiplomaDocumentList').and.callThrough();
        const response = { 'mock': 'mockResult' };

        multiFileUploadServiceMock.setResponse([{}]);
        afwHttp.setupOnlyResponse(response, 200);

        const result2 = diplomaService.getDiplomaDocumentList('spinnerText');
        result2.subscribe(() => {
            expect(spyHttp).toHaveBeenCalledWith(apiString, 'spinnerText');
            expect(spyDocumentList).toHaveBeenCalledWith('spinnerText');
            expect(spyDocumentList).not.toBeNull();

        });
        afwHttp.returnOnlyResponse();

    }));

    // tslint:disable-next-line:no-identical-functions
    it('It should return diplomaSnapshot', () => {
        diplomaStoreServiceMock.returnState(Object.assign({}, this.diplomaState));
        const diplomaState = diplomaService.getDiplomaSnapshot();
        expect(diplomaState).toEqual(Object.assign({}, this.diplomaState));
    });
});

У меня теперь это так:

it('It should return diploma from the snapshot as an observable ', () => {

        const expected = { code: '00100-00101', test: 'test' };
        afwHttp.setupOnlyResponse(expected, 200);
        const spyHttp = spyOn(afwHttp, 'get').and.callThrough();
        diplomaStoreServiceMock.returnState({diploma: expected});


        diplomaService.getDiploma('spinnerText').subscribe(result => expect(result['mock']).toEqual('mockResult'));
        afwHttp.returnOnlyResponse();
        expect(spyHttp).not.toHaveBeenCalledWith();

    });

Но тогда я получу эту ошибку:

Службы: DiplomaService> Должен возвращать диплом из снимка какОжидаемый ожидаемый неопределенный, равный 'mockResult'.Ошибка: ожидалось, что undefined равно «mockResult».at at SafeSubscriber._next (http://localhost:9877/src/app/shared/services/src/diploma.service.spec.ts?:65:93) at SafeSubscriber.push ... / .. / node_modules / rxjs / _esm5 / internal / Subscriber.js.SafeSubscriber .__ tryOrUnsub (http://localhost:9877/E:/Projects/Source/Repos/VLR/Web/vlrworkspace/node_modules/rxjs/_esm5/internal/Subscriber.js?:196:1) в SafeSubscriber.push.../../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next (http://localhost:9877/E:/Projects/Source/Repos/VLR/Web/vlrworkspace/node_modules/rxjs/_esm5/internal/Subscriber.js?:134:1)

Ах, ок.

У меня теперь есть вот так:

 it('It should return diploma from the snapshot as an observable ', () => {

        const expected = { 'mock': 'mockResult' };
        afwHttp.setupOnlyResponse(expected, 200);
        const spyHttp = spyOn(afwHttp, 'get').and.callThrough();
        diplomaStoreServiceMock.returnState({diploma: expected});


        diplomaService.getDiploma('spinnerText').subscribe(result => expect(result['mock']).toEqual('mockResult'));
        afwHttp.returnOnlyResponse();
        expect(spyHttp).not.toHaveBeenCalledWith();

    });

и все работает

...