angular-cli: Spy on jasmine function from an Angular library is not working
I have an Angular library containing functions like “export function myFunction”.
The project with the error have this library as a dependency and when I want to spy on the function, the error below is display:
myFunction is not declared writable or has no setter
Now the real world example:
A simple function from the library:
export function isNotEmptyString(value: any): value is string {
return _.isString(value) && !_.isEmpty(value);
}
The dts of this function once packaged:
export declare function isNotEmptyString(value: any): value is string;
To spy on the function, I must have an object at some point.
So I use a custom module import to achieve this.
The spy on error:
import * as MyLibfrom 'my-lib';
const isNotEmptyStringSpy = spyOn(MyLib, 'isNotEmptyString').and.returnValue(false);
And the error is:
isNotEmptyString is not declared writable or has no setter
Now, if I use a spyOnPropety
:
import * as MyLibfrom 'my-lib';
const isNotEmptyStringSpy = spyOnProperty(MyLib, 'isNotEmptyString').and.returnValue(() => false);
And the new error is:
isNotEmptyString is not declared configurable
I also tried to use differents module inside the tsconfig.json
compiler options.
Like commonjs
, CommonJS
, ES2015
and ESNext
.
There is no difference.
tsconfig.json
"compilerOptions": {
"module": "commonjs"
}
Does anyone have a suggestion?
I am stuck with this 😕
Thanks !
Environment:
"karma": "4.4.1"
"jasmine-core": "3.5.0"
"@angular/core": "9.0.5"
About this issue
- Original URL
- State: closed
- Created 4 years ago
- Reactions: 1
- Comments: 18 (1 by maintainers)
Adding “module”: “commonjs” in tsconfig.spec.json lets you spyOn exported functions in angular.
1.abc.spec.ts import * as MyLibfrom ‘my-lib’;
const isNotEmptyStringSpy = spyOn(MyLib, ‘isNotEmptyString’).and.returnValue(false);
Note that you need to add module in tsconfig.spec.json not in tsconfig.json.
@alan-agius4 ok, fine, so I must find a way with the dependencies as they are. Nonetheless, are you talking about Angular’s DI ? Because pure functions, as well as I am aware of, have nothing to do with the DI since there is no decorator to make them available as tokens.