【问题标题】:cannot read property 'pipe' of undefined - Angular 6无法读取未定义的属性“管道”-Angular 6
【发布时间】:2020-01-09 08:47:48
【问题描述】:

组件.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
        });
}

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()
    );
}

spec.ts

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

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

【问题讨论】:

    标签: angular unit-testing jasmine angular6 karma-jasmine


    【解决方案1】:

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

    你可能想在测试中做什么:

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

    【讨论】:

    • 使用这种方法,测试用例会通过,但代码覆盖率不会发生。有没有其他办法?
    • 如果你正在编写单元测试,你不应该在组件测试中真正调用你的服务。相反,您应该为组件编写单元测试并为服务编写单元测试。这种方法使测试更易于编写、阅读和维护。
    • 另一方面,如果你真的想调用你的服务方法,你必须正确地模拟this.http.get(url),因为你不想进行真正的http调用。例如看这篇文章来模拟http调用medium.com/netscape/…
    【解决方案2】:

    你有没有尝试过这样的异步函数:

    it('should test', fakeAsync(() => { // Add FakeAsync
        let test =  spyOn(myService, 'getData');
        component.myData();
        tick(); // Add this
        expect(test).toHaveBeenCalled();
    }))
    

    【讨论】:

    • 尝试了上面提供的解决方案,但仍然遇到同样的错误。
    【解决方案3】:

    试试这个:

    声明管道在ts文件中

    import { Component, OnInit, Input, Pipe } from '@angular/core';
    
    @Pipe({                   //use for filter pipe
      name: "dataFilter"
    })
    

    【讨论】:

    • 这与问题无关。 rxjs 管道和角管道完全不同
    猜你喜欢
    • 2021-02-27
    • 1970-01-01
    • 2018-06-01
    • 2019-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-13
    • 2019-03-25
    相关资源
    最近更新 更多