简体   繁体   English

Angular 4/5单元测试用例.toBe in Services

[英]Angular 4/5 unit test case .toBe in Services

I am trying to write test case for calling Service and getting response from HTTP. 我正在尝试编写测试案例以调用Service并从HTTP获得响应。 Reference 参考

Now the problem is as following : 现在问题如下:

expect(data.length).toBe(12); Even though data.length is 100, This code does not throw any exception 即使data.length为100,此代码也不会引发任何异常

it('Should call HTTP!', inject([SampleDataService], (sampleDataService) => {
  expect(100).toBe(12); //<== This gives me correct exception i.e Expected 100 to be 12.
  sampleDataService.getData().subscribe(
    (data) => {
      console.log('ngOnInit', data.length); // here data.length is 100
      expect(data.length).toBe(12); // This does not throw any exception
    });
}));

SampleDataService.ts SampleDataService.ts

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

@Injectable()
export class SampleDataService {

  constructor(private http:HttpClient) { }

  getData(){
    return this.http.get("http://jsonplaceholder.typicode.com/posts");
  }
}

app.component.spec.ts app.component.spec.ts

import { TestBed, async, ComponentFixture,inject } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { SampleDataService } from './services/sample-data.service';
import { HttpClientModule,HttpClient } from '@angular/common/http';

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule,
        HttpClientModule,
        FormsModule,
        ReactiveFormsModule
      ],
      declarations: [
        AppComponent
      ],
      providers:[SampleDataService]
    }).compileComponents();
  }));
  it('Should call HTTP!', inject([SampleDataService], (sampleDataService) => {
    expect(100).toBe(12);
    sampleDataService.getData().subscribe(
      (data) => {
        console.log('ngOnInit', data.length);
        expect(data.length).toBe(12);
      });
  }));
});

You typically want to mock Http calls during unit tests. 您通常希望在单元测试期间模拟Http调用。 But if really you don't want to, then since http is asynchronous, you need to only end the test once you received the response: 但是,如果您确实不想这么做,则由于http是异步的,因此仅在收到响应后才需要结束测试:

  it('Should call HTTP!', (done) => {
    const service = TestBed.get(SampleDataService);
    service.getData().subscribe(
      (data) => {
        console.log('ngOnInit', data.length);
        expect(data.length).toBe(12);
        done();
      });
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM