注入Jasmine

时间:2016-12-12 00:13:17

标签: angular jasmine

我正在使用typescript创建一个角度2应用程序,需要使用Jasmine测试服务。正如您在测试方法中看到的,我需要将http注入我的服务中才能正常工作。如何将HTTP注入我的服务。这是我所指的代码行

var _getCustomerService:GetCustomerService = new GetCustomerService(http);

服务方法

@Injectable()
export class GetCustomerService {

    constructor(private http: Http) { }

    private customerUrl = 'http://localhost:45870/api/getcustomer';

    getCustomer(): Observable<Customer[]> {

        return this.http.get(this.customerUrl)
            .map((res: Response) => res.json())
            .catch((error: any) => Observable.throw(error.json().error || 'Server Error'));
    }
}

茉莉花测试

describe("Service test", function () {

    it("check service", function () {
         var http: Http;
        var _getCustomerService: GetCustomerService = new GetCustomerService (http);
        _getCustomerService.getCustomer()
            .subscribe(
            (Customer: Customer[]) => {
                var customer: Customer[];
                customer = Customer;
                expect(customer).toBeDefined();
            });


    });

});

1 个答案:

答案 0 :(得分:0)

您不希望为测试提出真正的XHR请求,因此您需要为测试创建一个专门的on,您可以在其中为每个请求设置模拟响应。为此,您需要使用工厂创建自己的Http,并使用MockBackend

import { MockBackend, MockConnection } from '@angular/http/testing';
import { Http, HttpMdodule, XHRBackend, RequestOptions, Response, ResponseOptions
       } from '@angular/http';
import { TestBed, async } from '@angular/core/testing';

describe('..', () => {
  let backend: MockBackend;
  let service: GetCustomerService;

  beforeEach(() => {
    const injector = TestBed.configureTestingModule({
      imports: [HttpModule],
      providers: [
        GetCustomerService,
        RequestOptions,
        MockBackend,
        {
          provide: Http,
          deps: [MockBackend, RequestOptions],
          useFactory: (backend: MockBackend, options: RequestOptions) => {
            return new Http(backend, options);
          }
        }
      ]
    });

    backend = injector.get(MockBackend);
    service = injector.get(GetCustomerService);
  });
});

现在,在测试中,您希望订阅MockBackend的连接,以便在连接进入时发送响应

it('..', async(() => {
  backend.connections.subscribe((conn: MockConnection) => {
    conn.mockRespond(new Response(new ResponseOptions({ body: 'some body ' })));
  });

  service.getCustomer().subscribe((Customer: Customer[]) => {
    expect(customer).toBeDefined();
  });
}));

另见: