Mock Angular 4+服务错误

时间:2018-01-22 14:56:02

标签: angular karma-jasmine

我已经为我的测试创建了一个模拟服务,但是我想测试一下,当一个错误发生时,在一次测试中发生了什么以及该错误的后果。在Java中,当我使用模拟服务时,我可以使用,对于特定的测试方法,模拟服务使用when(mockservice.method).thenReturn(error)返回错误,我不确定如何在Jasmine中执行等效操作。这是我到目前为止所做的:

class MockManagerService {
  @Output()
  selectedEventObject: EventEmitter<any> = new EventEmitter();

  getAlertsAndMessagesData(): Observable<any> {
  const data = {alerts: ''};
  return Observable.of(data);
  }
}

describe('DataComponent', () => {
  let component: DataComponent;
  let fixture: ComponentFixture<DataComponent>;

beforeEach(async(() => {
TestBed.configureTestingModule({
  declarations: [ DataComponent ],
  imports: [DataTableModule, HttpClientModule],
  providers: [
    {
        provide: ManagerService,
        useClass: MockManagerService
    }
  ]
})
.compileComponents();
}));

beforeEach(() => {
  fixture = TestBed.createComponent(DataComponent);
  component = fixture.componentInstance;
  fixture.detectChanges();
});

it('should be created', () => {
expect(component).toBeTruthy();
});
});

我要测试的ManagerService代码部分是:

err => {
        this.managerService.processError(err);
        this.managerService.userLoggedIn.emit(false);
    });

我不需要测试.processError方法是否执行了它的操作,但我希望看看是否发出了该事件。

有没有办法做到这一点:

it('should process error', () => {
  // Java psuedo code to explain what I want to do in JavaScript
  when(MockManagerService.methodThatThrowsError).thenReturn(error);
  verify(event emitted to userLoggedIn emitter)
}

1 个答案:

答案 0 :(得分:2)

首先导入Http客户端的测试模块:

import { 
  HttpClientTestingModule, 
  HttpTestingController // We'll need it
} from '@angular/common/http/testing';


imports: [HttpClientTestingModule],

然后,在您的测试中(或者在每个测试之前),像这样获取http控制器

const httpMock = TestBed.get(HttpTestingController); 

现在,您可以简单地模拟一个响应或类似的错误

myService.myMethod().subscribe(
  data => {/* expects */}
  err => {/* expects */}
);
const request = httpMock.expectOne(service.URL + 'your_url');
// make your expectations about the request here
expect(request.request.method).toEqual('GET');
// use either of them in a test, not both ! 
// -----------------------------
request.flush(/* data to return in success */);
request.error(new ErrorEvent('error string here');
// -----------------------------
httpMock.verify();