I have a helper file with multiple function:
myHelpers.ts
export function fn1(a, b) {
return a * b;
}
export function fn2(a, b) {
return a + b;
}
export function fn3(a, b) {
return a - b;
}
The above file, as well are others are bundled as a module and exported in the index.ts as
import * as Helpers from '/myHelpers';
export { Helpers };
I consume the above module in my app package.json as:
"helper-utils": "file:/local/app/helper"
Which my angular component uses:
import { Helpers } from 'helper-lib';
export class MyComponent {
constructor() {}
public btnClick(p1, p2) {
let value = Helpers.fn1(p1, p2);
console.log(value);
return value;
}
}
The above works fine and if on btnClick() in the GUI i pass 1 and 2, i see the value of 2 in the console.log.
Unit test:
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { MyComponent } from './myComponent';
import { Helpers } from 'helper-lib';
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({declarations:[MyComponent]}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should calc value', () => {
let mySpy = spyOn(Helpers, 'fn1');
let value = component.btnClick(1, 2);
expect(mySpy).toHaveBeenCalled();
});
});
Error:
Error: <spyOn> : fn1 is not declared writable or has no setter
from Mocking / Spying helper function in Angular Unit tests
No comments:
Post a Comment