无法读取未定义的属性“管道” - Angular 6

su1*_*212 4 unit-testing jasmine karma-jasmine angular angular6

组件.ts

// Component containing function
Public myData(){
    this.myService.getData()
        .pipe(
            take(1),
            catchError((err: any) => {
                this.myRows = [];
                return throwError(err);
            }),
            finalize(() => {
                console.log('In Finally');
            })
        )
        .subscribe((rows) => {
            this.myRows = rows;
            // Do something
        });
}
Run Code Online (Sandbox Code Playgroud)

myService.ts

// Service Call
public getData(): Observable < customer[] > {
    const url = 'some url';
    return this.http.get(url).pipe(
        map(this.checkForError),
        catchError((err: HttpErrorResponse) => {
            return throwError(err);
        }),
        map(this.myJson),
        share()
    );
}
Run Code Online (Sandbox Code Playgroud)

规格

    // Test Case
    it('should test', () => {
        let test =  spyOn(myService, 'getData');
        component.myData();
        expect(test).toHaveBeenCalled();
    });
Run Code Online (Sandbox Code Playgroud)

无法解决此错误。无法找到一种简单的方法来编写服务调用的测试用例。我们如何解决管道错误?

Abe*_*bel 5

错误似乎是this.myService.getData().pipe(...
因为在您的测试中,您监视“getData”,但您没有返回任何值,特别是不是来自间谍的可观察值。

您在测试中可能想要做什么:

const customers = []; // define here your testing array
spyOn(myService, 'getData').and.returnValue(of(customers)); // "of" is a Rxjs function to create an Observable
Run Code Online (Sandbox Code Playgroud)

  • 如果您正在编写单元测试,那么您不应该真正在组件测试中调用您的服务。相反,您应该为组件编写单元测试,并为服务编写单元测试。这种方法使测试更容易编写、阅读和维护。 (2认同)