Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Angular2 – 单元测试Observable错误“无法读取未定义的属性’subscribe’”大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有@L_674_1@服务函数,它返回Observable,我正在我的@L_674_1@组件中使用该服务.我使用 here发布的技术为组件编写了@L_674_1@单元测试.然而,奇怪的是我得到了“无法读取未定义的属性订阅’”.

被测组件:

@Component({
    modulEID: module.id,templateUrl: 'signup.component.html'
})
export class SignupComponent implements OnInit {
    signupForm: FormGroup;
    submitted = false;    
    registered = false;

    constructor(public router: Router,private fb: FormBuilder,public authservice: AuthservicE) {        

        this.signupForm = this.fb.group({
            'firstName': ['',Validators.required],'lastName': ['','email': ['',Validators.compose([Validators.required])],'password': ['','confirmpassword': ['',Validators.required]
        });
    }

    ngOnInit() {       
    }

    signup(event: any) {
        event.preventDefault();
        this.submitted = true;

        if (!this.signupForm.valid) return;

        this.authservice.register(this.signupForm.value)
            .subscribe(
            (res: ResponsE) => {
                if (res.ok) {
                    this.registered = true;
                }
            },(error: any) => {
                this.registered = false;                
                console.log (error.status + ': ' + error.messagE);
            });
    }
}

AbstractmockObservableservice

import { Subscription } from 'rxjs/Subscription';

export abstract class AbstractmockObservableservice {
    protected _subscription: Subscription;
    protected _fakeContent: any;
    protected _fakeError: any;

    set error(err: any) {
        this._fakeError = err;
    }

    set content(data: any) {
        this._fakeContent = data;
    }

    get subscription(): Subscription {
        return this._subscription;
    }

    subscribe(next: Function,error?: Function,complete?: Function): Subscription {
        this._subscription = new Subscription();
        spyOn(this._subscription,'unsubscribe');

        if (next && this._fakeContent && !this._fakeError) {
            next(this._fakeContent);
        }
        if (error && this._fakeError) {
            error(this._fakeError);
        }
        if (completE) {
            complete();
        }
        return this._subscription;
    }
}

最后是单元测试

import { ComponentFixture,TESTBed,async,fakeAsync,tick } from '@angular/core/tesTing';
import { By } from '@angular/platform-browser';
import { DebugElement,Component,NO_ERRORS_scheR_526_11845@A } from '@angular/core';
import { LOCATIOn } from '@angular/common';
import { Router } from '@angular/router';
import { FormBuilder } from "@angular/forms";

import { SignupComponent } from './signup.component';
import { Authservice } from "../index";
import { AbstractmockObservableservice } from './abstract-mock-observable-service'

let validUser = {
    firstName: "Ahmad",lastName: "Qarshi",email: "qarshi@gmail.com"
    password: "ahmad#123",confirmpassword: "ahmad#123" 
}

class Routerstub {
    navigate(url: String) { return url; }
}

class LOCATIOnstub {
    path(url?: String) { return '/security/login'; }
}

class Authservicestub extends AbstractmockObservableservice {
    register(model: any) {
        return this;
    }
}

let authservicestub: Authservicestub;
let comp: SignupComponent;
let fixture: ComponentFixture<SignupComponent>;
let de: DebugElement;
let el: HTMLElement;


function updateForm(firstName: String,lastName: String,email: String
    password: String,confpassword: String) {
    comp.signupForm.controls['firstName'].SETVALue(firstName);
    comp.signupForm.controls['lastName'].SETVALue(lastName);
    comp.signupForm.controls['email'].SETVALue(email);    
    comp.signupForm.controls['password'].SETVALue(password);
    comp.signupForm.controls['confirmpassword'].SETVALue(confpassword);    
}

describe('SignupComponent',() => {
    beforeEach(() => {
        TESTBed.configureTesTingModule({
            declarations: [SignupComponent],scheR_526_11845@as: [NO_ERRORS_scheR_526_11845@A]
        });
    });
    compileAndCreate();
    tests();
});

function compileAndCreate() {
    beforeEach(async(() => {
        authservicestub = new Authservicestub();
        TESTBed.configureTesTingModule({
            providers: [
                { provide: Router,useClass: Routerstub },{ provide: LOCATIOn,useClass: LOCATIOnstub },{ provide: Authservice,useValue: authservicestub },FormBuilder
            ]
        })
            .compileComponents().then(() => {
                fixture = TESTBed.createComponent(SignupComponent);
                comp = fixture.componenTinstance;
            });
    }));
}

function tests() {
    it('should call register user on submit',fakeAsync(() => {
        comp.submitted = false;
        updateForm(validUser.firstName,validUser.lastName,validUser.email,validUser.username,validUser.password,validUser.confirmpassword,validUser.Tin,validUser.userTypE);

        spyOn(authservicestub,'register');
        authservicestub.content = { ok: true };

        fixture.detectChanges();
        tick();
        fixture.detectChanges();

        fixture.debugElement.query(By.css('input[type=submit]')).nativeElement.click();


        expect(comp.submitted).toBeTruthy('request submitted');
        expect(authservicestub.register).toHaveBeenCalled();
        expect(comp.registered).toBeTruthy('user registered');
    }));
}

解决方法

当您监视服务方法并期望被调用时,您应该在spyOn上添加.and.callThrough().

你的代码应该是这样的:spyOn(authservicestub,’register’).and.callThrough();

然后,期望有BeenCalled().

看看:http://blog.danieleghidoli.it/2016/11/06/testing-angular-component-mock-services/

大佬总结

以上是大佬教程为你收集整理的Angular2 – 单元测试Observable错误“无法读取未定义的属性’subscribe’”全部内容,希望文章能够帮你解决Angular2 – 单元测试Observable错误“无法读取未定义的属性’subscribe’”所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。