【问题标题】:Angular 4/5 unit test case .toBe in ServicesAngular 4/5 单元测试用例 .toBe in Services
【发布时间】:2018-04-30 22:52:28
【问题描述】:

我正在尝试编写测试用例来调用服务并从 HTTP 获取响应。 Reference

现在问题如下:

expect(data.length).toBe(12); 即使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

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

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);
      });
  }));
});

【问题讨论】:

    标签: angular unit-testing angular-unit-test


    【解决方案1】:

    您通常希望在单元测试期间模拟 Http 调用。但是如果你真的不想这样做,那么由于 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();
          });
      });
    

    【讨论】:

    • 您的代码运行起来非常棒,但是您能告诉我我的代码有什么问题吗?
    • 该方法在您发送请求后立即返回,因此 Jasmine 不知道您正在等待接收和检查异步响应。
    • 但是我在那里使用了.subscribe,所以这不应该发生对吧?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-16
    • 2017-11-18
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多