Angular2-单元测试可观察到的错误“无法读取未定义的属性'subscribe'”

AJ加尔希

我有一个正在返回的服务功能,Observable并且正在其中一个组件中使用该服务。我已经使用此处发布的技术为组件编写了单元测试但是,奇怪的是,我收到“无法读取未定义的属性'subscribe'”。

被测组件:

@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': ['', Validators.required],
            'email': ['', Validators.compose([Validators.required])],            
            'password': ['', Validators.compose([Validators.required])],
            '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_SCHEMA } 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: "[email protected]"
    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],
            schemas: [NO_ERRORS_SCHEMA]
        });
    });
    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');
    }));
}
阿尔伯特·佩雷斯·法雷斯

当您侦察服务方法并希望被调用时,应添加.and.callThrough()spyOn。

您的代码应如下所示: spyOn(authServiceStub, 'register').and.callThrough();

然后,expect to haveBeenCalled()

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

运行npm测试(Angular 2单元测试)后无法读取未定义的属性“ subscribe”

Angular2 http.get(),map(),subscribe()和可观察模式-基本理解

Angular2 @ TypeScript可观察到的错误

angular2指令“无法读取未定义的属性” subscribe”,带有输出元数据

无法读取离子2单元测试中未定义的属性'_getPortal'

Angular2-无法读取嵌套调用中未定义的属性“ subscribe”

Angular 2单元测试可观察到的错误(HTTP)

Angular 2单元测试-无法读取未定义的属性“ root”

Angular2 Karma测试显示“ TypeError:this._subscribe不是函数”

Angular 2单元测试“无法读取未定义的属性'unsubscribe'”

Angular 2组件中的单元测试“成功”和“错误”可观察到的响应

Angular2可观察到的问题,无法读取未定义的属性“订阅”

Angular 2单元测试错误无法获取未定义或空引用的属性“ preventDefault”

Angular 4单元测试错误“ TypeError:无法读取未定义的属性'subscribe'”

TypeError:在angular2中执行单元测试时,无法读取未定义故障的属性“快照”

ng2-translate:无法读取TranslatePipe.transform中未定义的属性“ subscribe”

Angular无法读取未定义的属性“ subscribe”

angular2单元测试:无法读取componentInstance.method()的属性未定义

Angular 2无法读取未定义类型的属性“ subscribe”:无法读取未定义的属性“ subscribe”

角度组件测试错误:TypeError无法读取未定义的属性“ subscribe”

无法读取Ionic 4(Angular 8)上未定义的属性“ subscribe”

单元测试中的角度“无法读取未定义的属性'subscribe'”

Angular 9 TypeError:无法读取未定义的属性“ subscribe”

单元测试 Angular 4 出现错误“TypeError:无法读取未定义的属性“订阅”

类型错误:在单元测试 Angular 6 时无法读取未定义的属性“查询”

Angular 单元测试为 Http Post 返回“无法读取未定义的属性”

Angular 8:ActivatedRoute 上的 Jasmine 单元测试,TypeError:无法读取未定义的属性“父”

Angular 单元测试 - TypeError:无法读取未定义的属性“名称”

Angular 单元测试自定义验证器无法读取未定义的属性(读取“dobLengthValidator”)