我正在尝试测试一个组件。在另一篇文章中,我询问了测试直接函数调用。在这里,我使用相同的示例组件来关注组件的错误处理。
我想测试,当我的服务返回一个可观察的错误时,我的组件正确地调用了console.error(错误)。
如何“创建”此错误触发器并测试我的组件正确处理它。我听说间谍可以这样做,但我不知道在哪里设置这个间谍。
我想模拟服务上的http请求可能失败的情况。出于任何原因或任何错误代码。
以下是组件,存根服务和我的spec文件的代码。
import { NO_ERRORS_SCHEMA } from '@angular/core';
import {
async,
fakeAsync,
ComponentFixture,
TestBed,
tick,
inject
} from '@angular/core/testing';
import { Observable } from 'rxjs/Observable';
// Components
import { UserListComponent } from './user-list.component';
// Services
import { UserManagementService } from '../../shared/services/global.api';
import { UserManagementServiceStub } from '../../testing/services/global.api.stub';
let comp: UserListComponent;
let fixture: ComponentFixture<UserListComponent>;
let service: UserManagementService;
describe('UserListComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [UserListComponent],
imports: [],
providers: [
{
provide: UserManagementService,
useClass: UserManagementServiceStub
}
],
schemas: [ NO_ERRORS_SCHEMA ]
})
.compileComponents();
}));
tests();
});
function tests() {
beforeEach(() => {
fixture = TestBed.createComponent(UserListComponent);
comp = fixture.componentInstance;
service = TestBed.get(UserManagementService);
});
it(`should be initialized`, () => {
expect(fixture).toBeDefined();
expect(comp).toBeDefined();
});
it(`should get the user List after ngOnInit`, async(() => {
fixture.detectChanges();
expect(comp.userList.length).toBe(3, 'user list exists after init');
}));
}
import { Observable } from 'rxjs/Observable';
export class UserManagementServiceStub {
getListUsers() {
return Observable.from([
{
count: 3,
objects:
[
{
id: "7f5a6610-f59b-4cd7-b649-1ea3cf72347f",
name: "user 1",
group: "any"
},
{
id: "d6f54c29-810e-43d8-8083-0712d1c412a3",
name: "user 2",
group: "any"
},
{
id: "2874f506-009a-4af8-8ca5-f6e6ba1824cb",
name: "user 3",
group: "any"
}
]
}
]);
}
}
:cd /new/directory
答案 0 :(得分:3)
如果我理解您只需要一种从存根服务返回错误的方法,那么您可以创建一个单独的存根,它返回一个Observable错误,然后在检查错误处理的测试中使用它:
export class UserManagementServiceErrorStub {
getListUsers() {
return Observable.throw(new Error('Test error'));
}
}
这里有一篇关于使用Observables测试Angular服务的非常好的文章: https://mathiasbynens.be/notes/localstorage-pattern
更新 - 01/06/2019 RxJS 6
import { throwError } from 'rxjs';
class UserManagementServiceErrorStub {
getListUsers() {
return throwError(new Error('Test error'));
}
}