试图在测试文件中订阅一个http调用,我需要在测试中断言可观察的对象。

问题描述 投票:-1回答:1

我需要在我的测试中进行一个HTTP调用,我需要验证我的observable。

当我调试代码时,HTTP调用在服务中被调用,但在我的测试中,它失败了,它说http是 undefined但在调试时,我可以在控制台中看到http的观察结果。

          //service.ts file 
         //imports modles goes here 



  export class DataService {
      private api = this.configService.config.apiUrl;

  constructor(private http: HttpClient,
        private configService: AppConfigService,
        private errorService: ErrorService) 
          { 
          }
          public getCustomerList(): Observable<IUserResponse> {
                     return this.http.get<IUserResponse>`${this.api}/v1/getusers/users`);
      }

    }


 my test file serviec.specs.ts

  describe('OnboardingService', () => {
      beforeEach(() => {

     const httpClient = new HttpClient(new HttpXhrBackend({ build: () => new XMLHttpRequest() }));

    appConfigService= new AppConfigService(httpClient);

    appConfigService.config = { apiUrl:"https://test-test-getuser.json"}

    erroService = new ErrorService();

   service = new Dataservice(httpClient, appConfigService,erroService);
   it('should return an Observable<Iuser[]>', done => {

               service.getCustomerList().subscribe(response => {
          expect(response.users).toBeGreaterThan(0);
          done();
        });


    });
})
javascript node.js angular angular6
1个回答
0
投票

试试这个

this.http.get(`${this.apiurl}/v1/getuser`).subscribe((response)=>{console.log(response.user)})

0
投票

enter image description here

右边灰色箭头显示你要执行的代码。左边灰色箭头表示执行的结果。控制台日志在开发工具中没有箭头。

enter image description here

执行结果 .subscribe() 是一个Subscriber,你可以在你的截图中注意到。你的代码只是没有执行你传递给 .subscribe().

所以你的问题可能是你的端点。检查你的开发工具中的网络标签。

© www.soinside.com 2019 - 2024. All rights reserved.