Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular HttpErrorResponse:api url jasmine测试的Http失败响应_Angular_Unit Testing_Jasmine - Fatal编程技术网

Angular HttpErrorResponse:api url jasmine测试的Http失败响应

Angular HttpErrorResponse:api url jasmine测试的Http失败响应,angular,unit-testing,jasmine,Angular,Unit Testing,Jasmine,我在测试api调用和返回错误时遇到困难 “HttpErrorResponse:0的Http失败响应” 我可以让它返回正确的结果 我基本上是在应用程序中获得推文和显示 我正在测试的服务: const TWITTER_KEY = makeStateKey('twitter'); @Injectable() export class SocialService { private twitter:any; private url = 'https://server.herokuapp.com/

我在测试api调用和返回错误时遇到困难

“HttpErrorResponse:0的Http失败响应”

我可以让它返回正确的结果

我基本上是在应用程序中获得推文和显示

我正在测试的服务:

const TWITTER_KEY = makeStateKey('twitter');
@Injectable()
export class SocialService {
  private twitter:any;
  private url = 'https://server.herokuapp.com/';
  constructor(private http: HttpClient,
              @Inject(PLATFORM_ID) private platformId,
              private transferState:TransferState) { }

  initTwitter(){
    this.twitter = this.transferState.get(TWITTER_KEY, null as any);
    let data;
      if (this.twitter) {
        data = this.transferState.get(TWITTER_KEY, null);
        console.log("data= "+data);
            this.transferState.remove(TWITTER_KEY);

            return Observable.of(data);
            }else{
              const httpOptions = {
                headers: new HttpHeaders({
                 'Content-Type': 'application/json',
               })
             };
              return this.http.get(this.url+'twitter/gettweets', httpOptions)
                  .map((response) => {
                    let data = response;


                     if (isPlatformServer(this.platformId)) {
                        this.transferState.set(TWITTER_KEY, data as any);
                      }
                    return data;
                  })
                  .catch((error) =>  Observable.throw(error) )

            }
      }

}
测试第一次测试很好,但一旦测试出错 '如果无法获取推文,则应返回错误' 我得到了上面的错误:

import { TestBed } from '@angular/core/testing';
import {HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing';
import { BrowserTransferStateModule } from '@angular/platform-browser';
import { SocialService } from './social.service';

describe('SocialService', () => {
  let httpMock: HttpTestingController;
  let service:SocialService;
  let apiURL:string
  let returnedResults:any
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [SocialService],
      imports:[BrowserTransferStateModule, HttpClientTestingModule]
    });
    service = TestBed.get(SocialService);
    httpMock = TestBed.get(HttpTestingController);
    apiURL = 'https://server.herokuapp.com/';
    returnedResults = [{created_at: "Jul 16 2018", id: 1, id_str: "1", text: "Twitter text1"}, {created_at: "Jul 17 2018", id: 2, id_str: "2", text: "Twitter text2"}]
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });

  it('should get Tweets', () => {
    service.initTwitter()
    .subscribe((response)=>{
      expect(response).toBeDefined();
      expect(response).toEqual(returnedResults);
      console.log(response)
    })
    const request = httpMock.expectOne(apiURL+'twitter/gettweets');
    expect(request.request.method).toEqual('GET');
    request.flush(returnedResults);
    httpMock.verify();
  });

  it('should return error if cannot get Tweets', () => {
    service.initTwitter()
    .subscribe((response)=>{
      expect(response).toBeDefined();
      expect(response.failure.error.type).toBe('ERROR_GETTING_TWEETS');   
    })
    const request = httpMock.expectOne(apiURL+'twitter/gettweets');
    request.error(new ErrorEvent('ERROR_GETTING_TWEETS'));
    httpMock.verify();
  });
});

多亏了@jornsharpe,这就是我现在所做的

 it('should return error if cannot get Tweets', () => {
        service.initTwitter()
        .subscribe(()=>{
        }, error =>{
          expect(error.error.type).toBe('ERROR_GETTING_TWEETS'); 
          console.log(error.error.type) 
          Observable.throw(error)
        }
      ) 
        const request = httpMock.expectOne(apiURL+'twitter/gettweets');
        request.error(new ErrorEvent('ERROR_GETTING_TWEETS'));
        httpMock.verify();
      });

如果你在observable中抛出了一个错误,并在订阅的第二次回调中结束。非常感谢,它起了作用,我已经发布了,我如何更改了答案中的代码,但是如果你想将你的评论作为答案发布,我会将其标记为正确