我陷入了一个失败的单身,但我无法理解为什么。
所以我有一个我想测试的服务。一个简单的服务,发布到API网址。
以下是服务代码
import { Injectable } from '@angular/core';
import { Http, Response, RequestOptions, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { environment } from '../../../environments/environment';
import 'rxjs/add/operator/map';
import { ICarrierDetails } from './carrier-details';
@Injectable()
export class CarrierService {
apiGatewayCartUri = environment.cartApiUri;
constructor(private http: Http) { }
getCarriersDetails(): Observable<ICarrierDetails[]> {
return this.http.post(this.apiGatewayCartUri + 'carriers/', {})
.map((response: Response) => <ICarrierDetails[]>response.json());
}
}
这是我的spec文件:
import { CarrierService } from './carrier.service'
import { Observable } from 'rxjs/Observable';
import { environment } from '../../../environments/environment';
import 'rxjs/add/observable/of';
describe('CarrierService', () => {
let carrierService: CarrierService;
let mockHttp;
let apiGatewayCartUri;
beforeEach(() => {
apiGatewayCartUri = environment.cartApiUri;
mockHttp = jasmine.createSpyObj('mockHttp', ['post'])
carrierService = new CarrierService(mockHttp)
});
describe('Should call http.post method with the right URL', () => {
mockHttp.post.and.returnValue(Observable.of(false));
carrierService.getCarriersDetails();
expect(mockHttp.post).toHaveBeenCalledWith(apiGatewayCartUri + 'carriers/', {});
});
});
这是我在控制台一直得到的例外:
Chrome 59.0.3071(Mac OS X 10.12.5)CarrierService应该使用正确的URL调用http.post方法遇到声明异常FAILED TypeError:无法读取属性&#39; post&#39;未定义的 在套房。 (http://localhost:9883/_karma_webpack_/main.bundle.js:97:17) 在ZoneDelegate.webpackJsonp ... / .. / .. / .. / zone.js / dist / zone.js.ZoneDelegate.invoke(http://localhost:9883/_karma_webpack_/polyfills.bundle.js:10672:26) 在Zone.webpackJsonp ... / .. / .. / .. / zone.js / dist / zone.js.Zone.run(http://localhost:9883/_karma_webpack_/polyfills.bundle.js:10464:43) 在套房。 (http://localhost:9883/_karma_webpack_/vendor.bundle.js:2195:29) 在Env.jasmineEnv。(匿名函数)[如描述](http://localhost:9883/_karma_webpack_/vendor.bundle.js:2172:38) 在套房。 (http://localhost:9883/_karma_webpack_/main.bundle.js:96:5) 在ZoneDelegate.webpackJsonp ... / .. / .. / .. / zone.js / dist / zone.js.ZoneDelegate.invoke(http://localhost:9883/_karma_webpack_/polyfills.bundle.js:10672:26) 在Zone.webpackJsonp ... / .. / .. / .. / zone.js / dist / zone.js.Zone.run(http://localhost:9883/_karma_webpack_/polyfills.bundle.js:10464:43) 在套房。 (http://localhost:9883/_karma_webpack_/vendor.bundle.js:2195:29)
答案 0 :(得分:0)
我认为您的问题出在beforeEach
方法中。它应该是异步功能。
尝试使用它:
import { async } from '@angular/core/testing';
beforeEach(async(() => {
apiGatewayCartUri = environment.cartApiUri;
mockHttp = jasmine.createSpyObj('mockHttp', ['post']);
carrierService = new CarrierService(mockHttp);
}));