繁体   English   中英

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

[英]undefined is not an object in Observable response in service stub [Jasmine]

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

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

对我的任何见识都可以帮助我理解问题所在,并且最好的方法是进行此测试。 我已经搜索了过去两个小时的网站,希望这不是重复的问题。

我在很大程度上遵循此指南: https : //angular.io/guide/testing
角5.0.0
茉莉花2.6.2
业力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)

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

暂无
暂无

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

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