使用Angular 2和Jasmine / Karma测试真正的后端服务

时间:2017-02-16 16:46:00

标签: angular karma-jasmine

我想在我的Angular2应用程序的rails后端api的测试实例之间进行一些基本的端到端测试。 (我刚刚开始)。

我使用cli和服务(也使用cli)创建了应用程序。 我向服务添加了一个方法来尝试发出请求和规范来测试它但是我可以在控制台中看到Krama浏览器窗口请求不会转到ip我希望它去,而不是去看似是业力的“服务员”。

使用此设置时,有什么方法可以将http请求定向到特定的IP?

我想测试的服务

import { Injectable, Inject } from '@angular/core';
import { Http, Response } from '@angular/http';

import { Observable }     from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/share';

@Injectable()
export class RailsBackendService {

  private mainToken = "some_api_access_token";
  private tokenQueryKey = "api_access_token";

  constructor(private http: Http) { }

  get token(): string {
    return this.mainToken;
  }

  getUserList() : Observable<any> {
    console.log("getting user list");
    const querySting = `${this.tokenQueryKey}=${this.token}`;
    const requestURL = `http:172.16.1.114/api/v1/users/?${querySting}`;
    this.http.get(requestURL).subscribe();
    return this.http.get(requestURL);
  }

}

规范

import { TestBed, async, inject } from '@angular/core/testing';
import { HttpModule, Http } from '@angular/http';
import { RailsBackendService } from './rails-backend.service';
import { ReflectiveInjector } from '@angular/core';

describe('RailsBackendService', () => {

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpModule],
      providers: [RailsBackendService]
    });
  });

  it('should ...', inject([RailsBackendService], (service: RailsBackendService) => {
    expect(service).toBeTruthy();
  }));

  it('should exist', inject([RailsBackendService], (service: RailsBackendService) => {
    console.log('here2');
    expect(service.getUserList().subscribe( 
      (x) => {console.log("next",x);},
      (x) => {console.log("error triggered",x, "error done");},
      () => {console.log("complete",x);}
      )).toBe('x');
    }
  ));
});

控制台响应

请注意所需IP地址前面的localhost:9876。

enter image description here

1 个答案:

答案 0 :(得分:1)

Web应用将指定的URL视为相对URL并将其连接到请求中的当前基本URL的最明显原因是该协议未被指定。

确实,这是不正确的:

const requestURL = `http:172.16.1.114/api/v1/users/?${querySting}`;

应为http://...