【问题标题】:Mock Angular 4+ service error模拟 Angular 4+ 服务错误
【发布时间】:2018-01-22 14:56:02
【问题描述】:

我为我的测试创建了一个模拟服务,但我想测试在一个测试中发生错误时会发生什么以及该错误的后果。在 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)
}

【问题讨论】:

    标签: angular karma-jasmine


    【解决方案1】:

    首先导入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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-09
      • 2018-06-01
      • 2018-03-19
      • 2018-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-15
      相关资源
      最近更新 更多