我正在尝试编写用于调用Service并从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);
});
}));
});
答案 0 :(得分:0)
您通常希望在单元测试期间模拟Http调用。但如果真的你不想,那么由于http是异步的,你需要在收到回复后才结束测试:
**<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/toolbar"
android:background="#353535"
app:tabMode="fixed"
android:minHeight="?attr/actionBarSize"
app:tabIndicatorColor="@color/red"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />**