我想测试一个返回observable的方法。我能够测试该方法,但我无法覆盖错误返回部分
home.component.ts
import { Data } from './../model/data.model';
import { DataService } from './../services/data.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
})
export class HomeComponent implements OnInit {
data: Data[];
errorMsg: any;
constructor(private service: DataService) {}
ngOnInit() {
this.getData();
}
getData() {
this.service.getData().subscribe(
(data) => {
console.log(data);
this.data = data;
},
(err) => {
this.errorMsg =err;
},
);
}
}
Home.component.spec.ts
import { Data } from './../model/data.model';
import { HttpClientModule } from '@angular/common/http';
import { HomeComponent } from './home.component';
import { ComponentFixture, async, TestBed, fakeAsync } from '@angular/core/testing';
import { DataService } from '../services/data.service';
import { Observable } from 'rxjs';
import 'rxjs/add/observable/of';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { results } from '../model/home';
class MockMyService {
public data: Data[];
public getData(): Observable<Data[]> {
this.data = results;
return Observable.of(this.data);
}
}
describe('HomeComponent', () => {
let component: HomeComponent;
let fixture: ComponentFixture<HomeComponent>;
let dataService: DataService;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [HomeComponent],
providers: [
{
provide: DataService,
useClass: MockMyService,
},
],
imports: [HttpClientModule],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
}).compileComponents();
fixture = TestBed.createComponent(HomeComponent);
component = fixture.componentInstance;
dataService = TestBed.get(DataService);
fixture.detectChanges();
});
describe('Given the component is loaded', () => {
describe('When getData returns mock data', () => {
it('Then the data attribute has a length of 2', (done) => {
dataService.getData().subscribe(
() => {
expect(component.data.length).toEqual(2);
done();
},
(err) => {
expect(component.errorMsg).toEqual(err);
},
);
});
});
});
it('testing error block', () => {
dataService.getData().subscribe(
(data) => {},
(err) => {
expect(component.errorMsg).toEqual(err);
},
);
});
});
results.model.ts
export const results = [
{
effectivefrom: '',
effectiveto: '',
externalname: 'SURVEY',
id: 1,
jhi_type: '',
name: ' Survey',
processstep: 1,
status: 'Initialization',
},
{
effectivefrom: '',
effectiveto: '',
externalname: '',
id: 2,
jhi_type: '',
name: ' Survey',
processstep: 1,
status: 'Initialization',
},
];
我已经通过了所有测试用例但是我无法覆盖错误块。
返回的错误是对象类型。
我怎样才能克服这个问题?提前致谢。
在这种情况下,因为你从this.getData();
调用了ngOnInit()
,所以你在从MockSvc创建它时没有太多控制方法。创建2个不同的Mock服务并使用如下
试试以下代码:
import { Data } from './../model/data.model';
import { HttpClientModule } from '@angular/common/http';
import { HomeComponent } from './home.component';
import { ComponentFixture, async, TestBed, fakeAsync } from '@angular/core/testing';
import { DataService } from '../services/data.service';
import { Observable } from 'rxjs';
import 'rxjs/add/observable/of';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { results } from '../model/home';
import { ErrorObservable } from 'rxjs/observable/ErrorObservable';
class MockMyService {
public data: Data[];
public getData(): Observable<Data[]> {
this.data = results;
return Observable.of(this.data);
}
}
class MockMyServiceWithError {
public data: Data[];
public getData(): Observable<Data[]> {
this.data = results;
return new ErrorObservable(this.data);
}
}
describe('HomeComponent', () => {
let component: HomeComponent;
let fixture: ComponentFixture<HomeComponent>;
let dataService: DataService;
describe('With Errored Response', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [HomeComponent],
providers: [
{
provide: DataService,
useClass: MockMyServiceWithError
}
],
imports: [HttpClientModule],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
}).compileComponents();
fixture = TestBed.createComponent(HomeComponent);
component = fixture.componentInstance;
dataService = TestBed.get(DataService);
fixture.detectChanges();
});
it('should be created',()=>{
expect(component).toBeDefined();
})
it('should have defined error message',()=>{
expect(component.errorMsg).toBeDefined();
})
});
describe('With Success Response', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [HomeComponent],
providers: [
{
provide: DataService,
useClass: MockMyService
}
],
imports: [HttpClientModule],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
}).compileComponents();
fixture = TestBed.createComponent(HomeComponent);
component = fixture.componentInstance;
dataService = TestBed.get(DataService);
fixture.detectChanges();
});
it('should be created',()=>{
expect(component).toBeDefined();
})
it('should have defined error message',()=>{
expect(component.errorMsg).toBeUndefined();
})
});
});
其他方式:
或者在组件中制作service
之后可能是类似下面的内容:
describe('Given the component is loaded', () => {
// make constructor(public service: DataService) {}
it('should expect defined error message',()=>{
spyOn(compponent.service,'getData').and.returnValue(new ErrorObservable('Error code'));
component.getData();
expect(component.errorMsg).toBe('Error code')
})
it('should expect getData to be called',()=>{
spyOn(compponent.service,'getData').and.callThrough();
component.getData();
expect(compponent.service.getData).toHaveBeenCalled();
})
});