【发布时间】:2017-12-19 16:12:03
【问题描述】:
我被困在一个失败的团结中,但我不明白为什么。
所以我有一个要测试的服务。一个简单的服务发布到 API url。
这是服务代码
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());
}
}
这是我的规范文件:
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:无法读取未定义的属性“帖子” 在套房。 (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)
【问题讨论】:
-
我认为这部分是错误的
carrierService = new CarrierService(mockHttp),你不能在单元测试中使用这样的服务。更多关于测试服务的扩展chariotsolutions.com/blog/post/…
标签: angular unit-testing karma-jasmine