用Jasmine静态数据模拟测试,类似于http调用Angular吗?

时间:2019-05-01 22:16:09

标签: angular jasmine mocking rxjs

我正在尝试为此调用Jasmine建立一个模拟测试。 由于调用handleSuccess方法而失败,但响应为undefined

AuthenticationService代码:

public login(cred): Observable<any> {

  const data = {};
  return this.http.post(this.url, data, { observe: 'response' }).map(
    response => this.handleSuccess(response)
  );
}

测试代码:

describe('AuthenticationService', () => {

beforeEach(() => {
    TestBed.configureTestingModule({
    providers: [
        AuthenticationService,
        { provide: HttpClient, useClass: MockHttpClient }
    ]
    });
});

it('should be created', inject([AuthenticationService], (service: AuthenticationService) => {
    spyOn<any>(service, 'handleSuccess').and.callThrough();
    expect(service).toBeTruthy();
    service.login({userId: 'XY12345', userPassword: 'password'})
    .subscribe((resp) => {
        expect(service['handleSuccess']).toHaveBeenCalled(); 
    });
  }));
});


class MockHttpClient {
  post(url: string, body: any, options: any) {
    return Observable.of({
      response: {
        headers: {},
        body: {}
      }
    });
  }
}

0 个答案:

没有答案