角度测试获取实际的HTTP响应 [英] Angular Testing Getting Actual HTTP Response

查看:79
本文介绍了角度测试获取实际的HTTP响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是角单元测试的新手.我想做的是从我的API获取实际结果.我检查了希望是有帮助的

I'm new to angular unit testing. What I want to do is getting actual results from my API. I checked this documentation but as I understand, I should create mock responses. Here is my code,

myService.ts:

...

public GetAll = (apiname: string): Observable<Object> => {

return this._http.get("foo/" + apiname,{headers:this.options}); //this.options = newHttpHeaders({'ContentType':'application/json','Accept':'application/json'});
}
...

myService.spec.ts:

...

beforeEach(() => {
    TestBed.configureTestingModule({
    imports: [
        HttpClientModule,
        HttpClientTestingModule
    ],
    providers: [
        MyService
    ]
    });  
});

afterEach(inject([HttpTestingController], (backend: HttpTestingController) => {
    backend.verify();
}));

it('GetAll() should work', () => {

    const testData = {id: "123"};

    service.GetAll("items").subscribe(data => { 
        //console.log(JSON.stringify(data));
    });

    const req = httpTestingController.expectOne('foo/items');
    expect(req.request.method).toEqual('GET');

    req.flush(testData);
    httpTestingController.verify();
});

When I write the result in console, it writes 'testData' instead of 'data'. As I said before, I want to get actual result from my API, not mock result. Sorry if it is a silly question but how can I do that ? Thanks for advice.

解决方案

Here is a working solution to get a real data

auth.service.te

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
interface Post {
  userId: number;
  id: number;
  title: string;
  body: string;
}
@Injectable({
  providedIn: 'root',
})
export class AuthService {
  constructor(private http: HttpClient) {}
  getPost(postId: number): Observable<Post> {
    return this.http.get<Post>(
      `https://jsonplaceholder.typicode.com/posts/${postId}`
    );
  }
}

auth.service.spec.ts

import { TestBed } from '@angular/core/testing';
import { AuthService } from './auth.service';
import { HttpClientModule } from '@angular/common/http';
interface Post {
  userId: number;
  id: number;
  title: string;
  body: string;
}
describe('AuthService', () => {
  let service: AuthService;
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientModule],
    });
    service = TestBed.inject(AuthService);
  });
  it('should get the data successfully', (done: DoneFn) => {
    service.getPost(1).subscribe((post: Post) => {
      console.log('data is ', post);
      expect(post.id).toEqual(1);
      done();
    });
  });
});

Hope is helps

这篇关于角度测试获取实际的HTTP响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆