首页 > 解决方案 > 如何在业力单元测试中调用 API post 方法并在 Angular 4 中获得响应

问题描述

我正在尝试以 Angular 4 编写业力单元测试用例,以从 post 方法获得响应。我需要来自 API 的数据来编写进一步的测试用例。我的示例代码片段如下运行,但我无法得到响应。

规格

  describe('Login service : ', () => {
  let component: LoginComponent;
  let fixture: ComponentFixture<LoginComponent>;


  beforeEach(async(() => {
  TestBed.configureTestingModule({
  imports: [
    HttpClientModule,
    HttpClientTestingModule
  ]
  })
  .compileComponents();
  }));

afterEach(inject([HttpTestingController], (backend: HttpTestingController) => {
backend.verify();
}));


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

debugElement = fixture.debugElement.query(By.css('#userName'));
htmlElement = debugElement.nativeElement;

 });

  it(`should emit 'true' for 200 Ok status `, async(inject([LoginService, HttpTestingController],
(service: LoginService, backend: HttpTestingController) => {
  service.login({ userName: 'CF09221601k', password: 'LK6XOMPBRkH0', BrowserInfo: 'chrome 46.0.2490.86' }).subscribe((next) => {
    expect(next).toBeTruthy();
  });
  backend.expectOne('api/ValidateClientLogin').flush(null,
    { status: 200, statusText: 'Ok' });
})));

登录服务.ts

export class LoginService {

constructor(private httpClient: HttpClient) { }

public login(user) {
    return this.httpClient.post(APPCONFIG.WEBSERVICE_URL + APIURL.ValidateClientLogin, user, {observe: 'response'});
}
}

标签: angularkarma-jasmine

解决方案


推荐阅读