Я хочу протестировать метод, возвращающий наблюдаемый. Я могу проверить метод, но не могу покрыть ошибку, возвращающую часть
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',
},
];
Я получаю все тесты, но не могу закрыть блок ошибок.
возвращаемая ошибка - тип объекта.
Как я могу преодолеть эту проблему? Заранее спасибо.