Subscribe块中的角度测试未运行

时间:2018-02-17 19:13:07

标签: angular jasmine

我正在尝试在Angular中测试服务,但我无法进入服务的订阅块,我无法弄清楚我做错了什么。这是我的服务:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import 'rxjs/add/operator/switchMap';

@Injectable()
export class MovieService {

  getNowPlaying() {
    return this.http.get('https://api.themoviedb.org/3/movie/now_playing?api_key=[MY KEY]&language=en&region=US').switchMap(res => {
      const page = Math.ceil(res['total_pages'] * Math.random());
      return this.http.get(`https://api.themoviedb.org/3/movie/now_playing?api_key=[MY KEY]&language=en&region=US&page=${page}`);
    });
  }

  constructor(private http: HttpClient) { }

}

我的测试:

describe('getNowPlaying', () => {
    it('should get a page of now playing movies from the api', async(
      inject([MovieService, HttpTestingController], (movieService: MovieService, backend: HttpTestingController) => {
        movieService.getNowPlaying().subscribe(res => {
          console.log('hi');
        });

        backend.expectOne({
          url: 'https://api.themoviedb.org/3/movie/now_playing?api_key=[MY KEY]&language=en&region=US',
          method: 'GET'
        });
      }),
    ));
})

backend.expectOne测试通过了,但我只想尝试记录' hi'到控制台显示我进入订阅块,没有任何记录。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

您无法在订阅块中看到任何代码,因为与setTimeout的情况一样,此代码将异步工作。 Angular有很好的开箱即用工具来处理异步测试:asyncfakeasync

如果您需要等待某些异步操作完成,只需将整个it案例包装到fakeasync并使用tick()。您将在本文中找到一个示例:https://medium.com/@paynoattn/simple-observable-unit-testing-in-angular2-43c4f4a0bfe2

<强>更新 如果您需要查看从API调用返回的内容,您可以简单地在订阅块之外声明一个变量,并在其内部为其分配响应。然后记录下来。

it('should get a page of now playing movies from the api', fakeAsync(
  inject([MovieService, HttpTestingController], (movieService: MovieService, backend: HttpTestingController) => {
    let response;

    movieService.getNowPlaying().subscribe(res => {
      response = res;
    });
    tick();

    expect(response).toEqual(...);

    backend.expectOne({
      url: 'https://api.themoviedb.org/3/movie/now_playing?api_key=[MY KEY]&language=en&region=US',
      method: 'GET'
    });
  }),
));