简体   繁体   中英

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

According to the Jasmine documentation , the Spy object has a method withArgs ()

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

I can`t find this method in the version adapted for TypeScript. My project was created with angular-cli(ng new), Jasmine was provided from the box. When I try to call the withArgs() method, Visual Code writes to me that this method does not exist in the Spy class...

It's likely that you are either using an old version of jasmine, or an old version of the jasmine typings library. This particular method was introduced in Jasmine 3.0 . Notice that in the Jasmine 2.9 docs , the method does not exist.

All you need to do is update your Jasmine and jasmine typings libraries. Assuming you are using npm, you can do something like this:

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.

In my case, updating the Jasmine library was no option within the delivery time span due to company policies. Hence I could not use withArgs. I solved it by using callFake and manually check the argument there.Like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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