[Angular7] [笑话]如何测试MergeMap?

时间:2019-03-05 20:28:21

标签: angular testing rxjs jestjs angular7

我需要您的帮助:)

我使用了angular 7和Rxjs。为了进行测试,我使用了Jest。

我的组件在2个httpClient之间使用MergeMap:

addPost() {
  this.postService.createPost(post).pipe(
    mergeMap( (response) => { return this.postService.getPost(response.headers.get('Location'));} )
  ).subscribe(
    (post) => {
      this.content =""; this.postService.addingPostToArray(post);
    }, (error) => {
      //todo
    }
  );
}

还有我的PostService:

createPost(post:Post) {
 return this.httpClient
   .post('http://localhost:8080/posts', {post: post}, {observe:  'response'}); 
}

getPost(url: any) {
   return this.httpClient.get<Post>(url);
}

然后我像这样对组件进行测试:

it('should test addPost OK', () => {
postService = TestBed.get(PostService);
spyOn(postService, 'createPost').and.returnValue(of('test'));
spyOn(postService, 'getPost').and.returnValue(of('test'));

component.addPost();

expect(postService.createPost).toHaveBeenCalled();
expect(postService.getPost).toHaveBeenCalled();

});

但是问题是我的getPost从未被调用。

expect(spy).toHaveBeenCalled()

Expected spy to have been called, but it was not called.

  131 |
  132 |     expect(postService.createPost).toHaveBeenCalled();
> 133 |     expect(postService.getPost).toHaveBeenCalled();

如何测试mergeMap?

我希望我的解释不要太怪异:)

感谢您的帮助;)

1 个答案:

答案 0 :(得分:0)

字符串测试将不具有属性response.headers.get('Location')。

尝试

spyOn(postService, 'createPost').and.returnValue(of({ headers: { get: _ => 'test' } }));
相关问题