简体   繁体   English

Jasmine + TypeScript,找不到Spy类的withArgs()方法

[英]Jasmine + TypeScript, can`t find the withArgs () method of the Spy class

According to the Jasmine documentation , the Spy object has a method withArgs ()根据 Jasmine 文档,Spy 对象有一个方法 withArgs()

spyOn (someObj, 'func'). withArgs (1, 2, 3) .and.returnValue (42);

I can`t find this method in the version adapted for TypeScript.我在适用于 TypeScript 的版本中找不到这种方法。 My project was created with angular-cli(ng new), Jasmine was provided from the box.我的项目是用 angular-cli(ng new) 创建的,Jasmine 是从盒子里提供的。 When I try to call the withArgs() method, Visual Code writes to me that this method does not exist in the Spy class...当我尝试调用 withArgs() 方法时,Visual Code 写信告诉我这个方法在 Spy 类中不存在......

It's likely that you are either using an old version of jasmine, or an old version of the jasmine typings library.您可能正在使用旧版本的 jasmine,或者旧版本的 jasmine 类型库。 This particular method was introduced in Jasmine 3.0 .这个特殊的方法是在Jasmine 3.0中引入的。 Notice that in the Jasmine 2.9 docs , the method does not exist.请注意,在Jasmine 2.9 文档中,该方法不存在。

All you need to do is update your Jasmine and jasmine typings libraries.您需要做的就是更新您的 Jasmine 和 jasmine 类型库。 Assuming you are using npm, you can do something like this:假设您使用的是 npm,您可以执行以下操作:

npm i -D jasmine@latest jasmine-core@latest @types/jasmine@latest

This updates all jasmine related libraries to their latest version and saves it as devDependencies.这会将所有与 jasmine 相关的库更新为其最新版本并将其保存为 devDependencies。

In my case, updating the Jasmine library was no option within the delivery time span due to company policies.就我而言,由于公司政策,在交付时间跨度内更新 Jasmine 库是不可能的。 Hence I could not use withArgs.因此我不能使用 withArgs。 I solved it by using callFake and manually check the argument there.Like this:我通过使用callFake解决了它并手动检查那里的参数。像这样:

mockAuthenticationService = jasmine.createSpyObj<AuthenticationService>('authenticationService', ['hasPermission']);
mockAuthenticationService.hasPermission.and.callFake((permission) => {
  return (permission === 'MyPermission');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM