mat-table not populated with data in test












0














As the title suggests, i am trying to test a method that fetches data from an api and then populates the mat-table with the data from the returned observable. However the mat-table is not populated; logging in the console the table html displays the table's html, but with the "tbody" tag empty, hence unpopulated.



The test error reads:
" Type ' to contain 'Vanilla Sky'"



Component.Spec



it('should display the film info in table', fakeAsync(() => {
const searchResults = new Array<ISearchItem>();
let filmMock = <ISearchItem>{
imdbID: 'tt0259711',
Title: 'Vanilla Sky',
Year: '2001',
Type: 'movie',
Poster: 'https://m.media-amazon.com/images/M/MV5BYzFlMTJjYzUtMWFjYy00NjkyLTg1Y2EtYmZkMjdlOGQ1ZGYwL2ltYWdlXkEyXkFqcGdeQXVyMTQxNzMzNDI@._V1_SX300.jpg'
};

searchResults.push(filmMock);

let searchResponse = <ISearchResponse>{
Search: searchResults,
totalResults: '1',
Response: 'True'
};

component.currentPaginationData = {
length: 1,
pageIndex: 1,
pageSize: 10,
previousPageIndex: 0
}

const imdbServiceStub: ImdbService = fixture.debugElement.injector.get(ImdbService);
let searchResponseObs = of(searchResponse);
spyOn(imdbServiceStub, 'searchImdbFilmDatabase').and.returnValue(of(searchResponseObs));

component.searchDatabaseByKeyword('sky', true);

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

table = fixture.debugElement.query(By.css('#filmList')).nativeElement;

console.log(table);

expect(imdbServiceStub.searchImdbFilmDatabase).toHaveBeenCalled();
expect(table.innerText).toContain(filmMock.Title);
}));


Component:



 searchDatabaseByKeyword(searchTerm: string, init?: boolean) {
let displayData: boolean = false;
let searchDbSub = this.imdbService.searchImdbFilmDatabase(searchTerm, this.currentPaginationData)
.pipe(
tap((data: ISearchResponse) => {
displayData = !(data.Response === 'False');
this.numberOfResults = parseInt(data.totalResults);

if (init) {
this.currentPaginationData = {
length: this.numberOfResults,
pageIndex: 1,
pageSize: 10,
previousPageIndex: 0
}
}
}),
map((data: ISearchResponse) => {
return data.Search
})
)
.subscribe((value: Array<ISearchItem>) => {
if (value && displayData) {
this.currentKeyword = searchTerm;
this.searchResults = value;

this.dataSource = new MatTableDataSource(this.searchResults);
this.dataSource.sort = this.sort;
this.paginator.length = this.numberOfResults;

if (init) {
this.dataSource.paginator = this.paginator;
this.paginator.pageIndex = this.currentPaginationData.pageIndex;
this.paginator.pageSize = this.currentPaginationData.pageSize;
}
}
}, (error: Error) => {
throw error;
});

this.subs.push(searchDbSub);
}


Service:



searchImdbFilmDatabase(searchTerm: string, paginationData?: IPaginatorData): Rx.Observable<any> {

let baseUrl = this.searchFilmDatabaseEp + "&s=" + searchTerm;
baseUrl += (paginationData) ? '&page=' + paginationData.pageIndex : '';
baseUrl += '&r=json&type=movie';

return this.http.get(baseUrl).pipe(
tap((data: ISearchResponse) => {

let tmp = this.store.select('searchReducer', 'searchData');
console.log(tmp);

}, (error: Error) => {
throw error;
})

);
}









share|improve this question





























    0














    As the title suggests, i am trying to test a method that fetches data from an api and then populates the mat-table with the data from the returned observable. However the mat-table is not populated; logging in the console the table html displays the table's html, but with the "tbody" tag empty, hence unpopulated.



    The test error reads:
    " Type ' to contain 'Vanilla Sky'"



    Component.Spec



    it('should display the film info in table', fakeAsync(() => {
    const searchResults = new Array<ISearchItem>();
    let filmMock = <ISearchItem>{
    imdbID: 'tt0259711',
    Title: 'Vanilla Sky',
    Year: '2001',
    Type: 'movie',
    Poster: 'https://m.media-amazon.com/images/M/MV5BYzFlMTJjYzUtMWFjYy00NjkyLTg1Y2EtYmZkMjdlOGQ1ZGYwL2ltYWdlXkEyXkFqcGdeQXVyMTQxNzMzNDI@._V1_SX300.jpg'
    };

    searchResults.push(filmMock);

    let searchResponse = <ISearchResponse>{
    Search: searchResults,
    totalResults: '1',
    Response: 'True'
    };

    component.currentPaginationData = {
    length: 1,
    pageIndex: 1,
    pageSize: 10,
    previousPageIndex: 0
    }

    const imdbServiceStub: ImdbService = fixture.debugElement.injector.get(ImdbService);
    let searchResponseObs = of(searchResponse);
    spyOn(imdbServiceStub, 'searchImdbFilmDatabase').and.returnValue(of(searchResponseObs));

    component.searchDatabaseByKeyword('sky', true);

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

    table = fixture.debugElement.query(By.css('#filmList')).nativeElement;

    console.log(table);

    expect(imdbServiceStub.searchImdbFilmDatabase).toHaveBeenCalled();
    expect(table.innerText).toContain(filmMock.Title);
    }));


    Component:



     searchDatabaseByKeyword(searchTerm: string, init?: boolean) {
    let displayData: boolean = false;
    let searchDbSub = this.imdbService.searchImdbFilmDatabase(searchTerm, this.currentPaginationData)
    .pipe(
    tap((data: ISearchResponse) => {
    displayData = !(data.Response === 'False');
    this.numberOfResults = parseInt(data.totalResults);

    if (init) {
    this.currentPaginationData = {
    length: this.numberOfResults,
    pageIndex: 1,
    pageSize: 10,
    previousPageIndex: 0
    }
    }
    }),
    map((data: ISearchResponse) => {
    return data.Search
    })
    )
    .subscribe((value: Array<ISearchItem>) => {
    if (value && displayData) {
    this.currentKeyword = searchTerm;
    this.searchResults = value;

    this.dataSource = new MatTableDataSource(this.searchResults);
    this.dataSource.sort = this.sort;
    this.paginator.length = this.numberOfResults;

    if (init) {
    this.dataSource.paginator = this.paginator;
    this.paginator.pageIndex = this.currentPaginationData.pageIndex;
    this.paginator.pageSize = this.currentPaginationData.pageSize;
    }
    }
    }, (error: Error) => {
    throw error;
    });

    this.subs.push(searchDbSub);
    }


    Service:



    searchImdbFilmDatabase(searchTerm: string, paginationData?: IPaginatorData): Rx.Observable<any> {

    let baseUrl = this.searchFilmDatabaseEp + "&s=" + searchTerm;
    baseUrl += (paginationData) ? '&page=' + paginationData.pageIndex : '';
    baseUrl += '&r=json&type=movie';

    return this.http.get(baseUrl).pipe(
    tap((data: ISearchResponse) => {

    let tmp = this.store.select('searchReducer', 'searchData');
    console.log(tmp);

    }, (error: Error) => {
    throw error;
    })

    );
    }









    share|improve this question



























      0












      0








      0







      As the title suggests, i am trying to test a method that fetches data from an api and then populates the mat-table with the data from the returned observable. However the mat-table is not populated; logging in the console the table html displays the table's html, but with the "tbody" tag empty, hence unpopulated.



      The test error reads:
      " Type ' to contain 'Vanilla Sky'"



      Component.Spec



      it('should display the film info in table', fakeAsync(() => {
      const searchResults = new Array<ISearchItem>();
      let filmMock = <ISearchItem>{
      imdbID: 'tt0259711',
      Title: 'Vanilla Sky',
      Year: '2001',
      Type: 'movie',
      Poster: 'https://m.media-amazon.com/images/M/MV5BYzFlMTJjYzUtMWFjYy00NjkyLTg1Y2EtYmZkMjdlOGQ1ZGYwL2ltYWdlXkEyXkFqcGdeQXVyMTQxNzMzNDI@._V1_SX300.jpg'
      };

      searchResults.push(filmMock);

      let searchResponse = <ISearchResponse>{
      Search: searchResults,
      totalResults: '1',
      Response: 'True'
      };

      component.currentPaginationData = {
      length: 1,
      pageIndex: 1,
      pageSize: 10,
      previousPageIndex: 0
      }

      const imdbServiceStub: ImdbService = fixture.debugElement.injector.get(ImdbService);
      let searchResponseObs = of(searchResponse);
      spyOn(imdbServiceStub, 'searchImdbFilmDatabase').and.returnValue(of(searchResponseObs));

      component.searchDatabaseByKeyword('sky', true);

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

      table = fixture.debugElement.query(By.css('#filmList')).nativeElement;

      console.log(table);

      expect(imdbServiceStub.searchImdbFilmDatabase).toHaveBeenCalled();
      expect(table.innerText).toContain(filmMock.Title);
      }));


      Component:



       searchDatabaseByKeyword(searchTerm: string, init?: boolean) {
      let displayData: boolean = false;
      let searchDbSub = this.imdbService.searchImdbFilmDatabase(searchTerm, this.currentPaginationData)
      .pipe(
      tap((data: ISearchResponse) => {
      displayData = !(data.Response === 'False');
      this.numberOfResults = parseInt(data.totalResults);

      if (init) {
      this.currentPaginationData = {
      length: this.numberOfResults,
      pageIndex: 1,
      pageSize: 10,
      previousPageIndex: 0
      }
      }
      }),
      map((data: ISearchResponse) => {
      return data.Search
      })
      )
      .subscribe((value: Array<ISearchItem>) => {
      if (value && displayData) {
      this.currentKeyword = searchTerm;
      this.searchResults = value;

      this.dataSource = new MatTableDataSource(this.searchResults);
      this.dataSource.sort = this.sort;
      this.paginator.length = this.numberOfResults;

      if (init) {
      this.dataSource.paginator = this.paginator;
      this.paginator.pageIndex = this.currentPaginationData.pageIndex;
      this.paginator.pageSize = this.currentPaginationData.pageSize;
      }
      }
      }, (error: Error) => {
      throw error;
      });

      this.subs.push(searchDbSub);
      }


      Service:



      searchImdbFilmDatabase(searchTerm: string, paginationData?: IPaginatorData): Rx.Observable<any> {

      let baseUrl = this.searchFilmDatabaseEp + "&s=" + searchTerm;
      baseUrl += (paginationData) ? '&page=' + paginationData.pageIndex : '';
      baseUrl += '&r=json&type=movie';

      return this.http.get(baseUrl).pipe(
      tap((data: ISearchResponse) => {

      let tmp = this.store.select('searchReducer', 'searchData');
      console.log(tmp);

      }, (error: Error) => {
      throw error;
      })

      );
      }









      share|improve this question















      As the title suggests, i am trying to test a method that fetches data from an api and then populates the mat-table with the data from the returned observable. However the mat-table is not populated; logging in the console the table html displays the table's html, but with the "tbody" tag empty, hence unpopulated.



      The test error reads:
      " Type ' to contain 'Vanilla Sky'"



      Component.Spec



      it('should display the film info in table', fakeAsync(() => {
      const searchResults = new Array<ISearchItem>();
      let filmMock = <ISearchItem>{
      imdbID: 'tt0259711',
      Title: 'Vanilla Sky',
      Year: '2001',
      Type: 'movie',
      Poster: 'https://m.media-amazon.com/images/M/MV5BYzFlMTJjYzUtMWFjYy00NjkyLTg1Y2EtYmZkMjdlOGQ1ZGYwL2ltYWdlXkEyXkFqcGdeQXVyMTQxNzMzNDI@._V1_SX300.jpg'
      };

      searchResults.push(filmMock);

      let searchResponse = <ISearchResponse>{
      Search: searchResults,
      totalResults: '1',
      Response: 'True'
      };

      component.currentPaginationData = {
      length: 1,
      pageIndex: 1,
      pageSize: 10,
      previousPageIndex: 0
      }

      const imdbServiceStub: ImdbService = fixture.debugElement.injector.get(ImdbService);
      let searchResponseObs = of(searchResponse);
      spyOn(imdbServiceStub, 'searchImdbFilmDatabase').and.returnValue(of(searchResponseObs));

      component.searchDatabaseByKeyword('sky', true);

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

      table = fixture.debugElement.query(By.css('#filmList')).nativeElement;

      console.log(table);

      expect(imdbServiceStub.searchImdbFilmDatabase).toHaveBeenCalled();
      expect(table.innerText).toContain(filmMock.Title);
      }));


      Component:



       searchDatabaseByKeyword(searchTerm: string, init?: boolean) {
      let displayData: boolean = false;
      let searchDbSub = this.imdbService.searchImdbFilmDatabase(searchTerm, this.currentPaginationData)
      .pipe(
      tap((data: ISearchResponse) => {
      displayData = !(data.Response === 'False');
      this.numberOfResults = parseInt(data.totalResults);

      if (init) {
      this.currentPaginationData = {
      length: this.numberOfResults,
      pageIndex: 1,
      pageSize: 10,
      previousPageIndex: 0
      }
      }
      }),
      map((data: ISearchResponse) => {
      return data.Search
      })
      )
      .subscribe((value: Array<ISearchItem>) => {
      if (value && displayData) {
      this.currentKeyword = searchTerm;
      this.searchResults = value;

      this.dataSource = new MatTableDataSource(this.searchResults);
      this.dataSource.sort = this.sort;
      this.paginator.length = this.numberOfResults;

      if (init) {
      this.dataSource.paginator = this.paginator;
      this.paginator.pageIndex = this.currentPaginationData.pageIndex;
      this.paginator.pageSize = this.currentPaginationData.pageSize;
      }
      }
      }, (error: Error) => {
      throw error;
      });

      this.subs.push(searchDbSub);
      }


      Service:



      searchImdbFilmDatabase(searchTerm: string, paginationData?: IPaginatorData): Rx.Observable<any> {

      let baseUrl = this.searchFilmDatabaseEp + "&s=" + searchTerm;
      baseUrl += (paginationData) ? '&page=' + paginationData.pageIndex : '';
      baseUrl += '&r=json&type=movie';

      return this.http.get(baseUrl).pipe(
      tap((data: ISearchResponse) => {

      let tmp = this.store.select('searchReducer', 'searchData');
      console.log(tmp);

      }, (error: Error) => {
      throw error;
      })

      );
      }






      angular rxjs karma-jasmine angular-material2






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 12 at 6:39

























      asked Nov 12 at 1:21









      vicgoyso

      226220




      226220
























          1 Answer
          1






          active

          oldest

          votes


















          0














          Whenever you have http calls ( You are subscribing to a method) due to async calls your table might not be populated. Try using something like:



          component.searchDatabaseByKeyword('sky', true);
          fixture.whenStable().then(() => {
          fixture.detectChanges();
          fixture.detectChanges();
          expect(imdbServiceStub.searchImdbFilmDatabase).toHaveBeenCalled();
          });





          share|improve this answer





















            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53254893%2fmat-table-not-populated-with-data-in-test%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            Whenever you have http calls ( You are subscribing to a method) due to async calls your table might not be populated. Try using something like:



            component.searchDatabaseByKeyword('sky', true);
            fixture.whenStable().then(() => {
            fixture.detectChanges();
            fixture.detectChanges();
            expect(imdbServiceStub.searchImdbFilmDatabase).toHaveBeenCalled();
            });





            share|improve this answer


























              0














              Whenever you have http calls ( You are subscribing to a method) due to async calls your table might not be populated. Try using something like:



              component.searchDatabaseByKeyword('sky', true);
              fixture.whenStable().then(() => {
              fixture.detectChanges();
              fixture.detectChanges();
              expect(imdbServiceStub.searchImdbFilmDatabase).toHaveBeenCalled();
              });





              share|improve this answer
























                0












                0








                0






                Whenever you have http calls ( You are subscribing to a method) due to async calls your table might not be populated. Try using something like:



                component.searchDatabaseByKeyword('sky', true);
                fixture.whenStable().then(() => {
                fixture.detectChanges();
                fixture.detectChanges();
                expect(imdbServiceStub.searchImdbFilmDatabase).toHaveBeenCalled();
                });





                share|improve this answer












                Whenever you have http calls ( You are subscribing to a method) due to async calls your table might not be populated. Try using something like:



                component.searchDatabaseByKeyword('sky', true);
                fixture.whenStable().then(() => {
                fixture.detectChanges();
                fixture.detectChanges();
                expect(imdbServiceStub.searchImdbFilmDatabase).toHaveBeenCalled();
                });






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 12 at 9:31









                sah1

                9013




                9013






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53254893%2fmat-table-not-populated-with-data-in-test%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    這個網誌中的熱門文章

                    Tangent Lines Diagram Along Smooth Curve

                    Yusuf al-Mu'taman ibn Hud

                    Zucchini