我使用Angular 2 Karma-Jasmine。 我有AService,
it("test", () => { let x:any = function1('value', aService); expect(x).toEqual("value1"); });现在AService有getA()方法,而function1使用了getA()方法。 我想要模拟AService.getA方法?
请告诉我嘲笑AService最佳方法?
I use Angular 2 Karma-Jasmine. I have AService,
it("test", () => { let x:any = function1('value', aService); expect(x).toEqual("value1"); });Now AService has getA() method, and function1 used getA() method. I want mock AService.getA method?.
Please tell me best ways for mocking AService ?
最满意答案
如果function的签名是接受AService类型
function1(value, service: AService) {}那么你需要确保模拟与AService兼容。 如果AService只有一个方法getA ,那么你真的只需要这样做
let mockA = { getA: () => { // mock implementation } }如果AService有更多的方法而不仅仅是getA而你不想实现它,那么你可以“模拟”模拟来输入AService 。
let mock = <AService>{ same as above }或者如果function1参数没有输入为AService ,那么你可以真正传递它。
另见 :
这篇文章给出了有关TypeScript结构类型系统的解释If function's signature is to accept AService type
function1(value, service: AService) {}then you need to make sure that the mock is compatible with AService. If AService only has one method getA, then you really only need to do
let mockA = { getA: () => { // mock implementation } }If AService has more methods than just the getA and you don't want to have to implement that, then you can "cast" the mock to type AService.
let mock = <AService>{ same as above }Or if the function1 parameter is not typed as AService, then you can really pass anything it.
See Also:
This post which gives an explanation about TypeScript's structural type system更多推荐
发布评论