Angular2模拟注射服务(Angular2 mocking injectable service)

编程入门 行业动态 更新时间:2024-10-22 05:00:10
Angular2模拟注射服务(Angular2 mocking injectable service)

我使用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

更多推荐

本文发布于:2023-08-04 12:14:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1415967.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:mocking   service   injectable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!