undefined不是服务存根中的Observable响应中的对象[Jasmine]

时间:2018-01-31 14:04:26

标签: angular unit-testing jasmine karma-runner observable

这是我第一次尝试在Angular中为服务编写测试,返回一个Observable。我收到的错误是' this.hubConnector.authenticate()。do' 未定义。

我不明白发生了什么。 isn Observable.of 足以提供Observable响应(也尝试使用 Observable.create 并手动创建Observable)?我应该使用间谍和.returnValue 吗?我是否错误地注入了服务或依赖项?

对我的任何见解都有助于我理解错误,并且非常感谢接受此测试的最佳方法。我在过去两个小时内搜索了这个网站,我希望这不是一个重复的问题。

我大部分时间都遵循本指南:https://angular.io/guide/testing
Angular 5.0.0
茉莉花2.6.2
Karma 1.7.0

服务。

import { Injectable } from '@angular/core';  
import { HubConnectorComponent } from 'angl-spawebbgrl/hub-connector-
component/hub-connector';  
import { Observable } from 'rxjs/Observable';  
import { SSOUser } from '../../shared/models/sso.model';  
import { EncriptionService } from 'angl-spawebbgrl/encription';  

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class AuthService {

private _usuario: SSOUser = null;

constructor(private hubConnector: HubConnectorComponent, private encriptionService: EncriptionService) {}

autenticar(): Promise<any> {

    this._usuario = null;

    return this.hubConnector
        .authenticate()
        .do((res: any) => {
            this._usuario = res;
            this.encriptionService.changeKeys();
            this.encriptionService.encrypt('yqb').subscribe((docCriptografado: string) => {});
        })
        .toPromise()
        .catch((err: any) => Promise.resolve());
}

    get usuario(): SSOUser {
        return this._usuario;
    }
}

测试。

import { AuthService } from './auth.service';  
import { SSOUser } from '../models/sso.model';  
import { ComponentFixture, TestBed, async, fakeAsync, tick } from
'@angular/core/testing';  
import { EncriptionService } from 'angl-spawebbgrl/encription';  
import { HubConnectorComponent } from 'angl-spawebbgrl/hub-connector-component/hub-connector';  
import { HubConnectorModule } from 'angl-spawebbgrl/spa-http-module/hub-connector.module';  
import { Observable } from 'rxjs/Observable';  
import 'rxjs/Rx';  

describe('AuthService', () => {
let authService: AuthService;
let encriptionService: EncriptionService;
let hubConnectorComponent: HubConnectorComponent;

beforeEach(() => {

    const hubConnectorComponentStub = {
        authenticate(): Observable<any> {
            return Observable.of(<SSOUser>{ user: 'X123456', id: '123456' });
        }
    };

    const encriptionServiceStub = {
        changeKeys(): void {},
        encrypt(valor: string): Observable<string> {
            return Observable.of('BZvebaV07yxksbkg1G4YWUGJuXlh39qThCTEPRQOLE8WnjH6JMGm7DdwQJkImRRF9kB728a/JG');
        }
    };

    TestBed.configureTestingModule({
        imports: [],
        declarations: [],
        providers: [
            AuthService,
            { provide: HubConnectorComponent, useValue: hubConnectorComponentStub },
            { provide: EncriptionService, useValue: encriptionServiceStub }
        ]
    });

    authService = TestBed.get(AuthService);
    encriptionService = TestBed.get(EncriptionService);
    hubConnectorComponent = TestBed.get(HubConnectorComponent);
});

it('test', fakeAsync(() => {

    spyOn(hubConnectorComponent, 'authenticate');
    console.log(authService);
    console.log(hubConnectorComponent);
    authService.autenticar();
    tick();
    expect(hubConnectorComponent.authenticate).toHaveBeenCalled();
}));
});

业力错误。

LOG: AuthService{hubConnector: Object{authenticate: function () { ... }}, encriptionService: Object{changeKeys: function () { ... }, encrypt: function (valor) { ... }}, _usuario: null}
LOG: Object{authenticate: function () { ... }}
PhantomJS 2.1.1 (Mac OS X 0.0.0): Executed 7 of 8 SUCCESS (0 secs / 3.569 secs)
PhantomJS 2.1.1 (Mac OS X 0.0.0) AuthService test FAILED
    TypeError: undefined is not an object (evaluating 'this.hubConnector
                .authenticate()
                .do') in http://local.jigsaw.dev.corp:9877/_karma_webpack_/main.bundle.js (line 157836)

1 个答案:

答案 0 :(得分:0)

删除spyOn(hubConnectorComponent,'authenticate');在测试中,因为您正在模拟此Provider方法并返回Observable Mock