I've tried this SO post, but it's not my case.
I have a service (AnimationService), which is depended on another service (AnimationStateService). This AnimationStateService has a getter state, which I want to mock in my test. So my test looks like this:
animation.service.spec.ts
describe("AnimationService", () => {
let animationService: SpyObj<AnimationService>;
let animationStateService: SpyObj<AnimationStateService>;
beforeEach(() => {
const spyAnimationStateService = createSpyObj("AnimationStateService", ["changeStatus"]);
TestBed.configureTestingModule({
providers: [
AnimationService,
{provide: AnimationStateService, useValue: spyAnimationStateService}
]
});
animationStateService = TestBed.get(AnimationStateService);
animationService = TestBed.get(AnimationService);
});
fit("should call changeStatus if status is AnimationStatus.Stopped", () => {
// Arrange
// animationStateService.status.and.returnValue(AnimationStatus.Stopped); - Doesn't work
// spyOnProperty(animationStateService, "status").and.returnValue(AnimationStatus.Stopped); - Doesn't work
// animationStateService.status = AnimationStatus.Stopped; - Works, but with TSLint error
// Act
animationService.start();
// Assert
expect(animationStateService.changeStatus).toHaveBeenCalled();
});
});
animation-state.service.spec.ts
@Injectable()
export class AnimationStateService {
public get status(): AnimationStatus { return this.state.animation.status; }
...
}
When I tried to mock the getter with:
animationStateService.status.and.returnValue(AnimationStatus.Stopped);
or with:
spyOnProperty(animationStateService, "status").and.returnValue(AnimationStatus.Stopped);
It doesn't worked. The getter simply doesn't returned the value I've been set.
This approach works:
animationStateService.status = AnimationStatus.Stopped;
but it gives me a TSLint error:
Cannot assign to 'status' because it is a constant or a read-only property.
So at this point I don't know, what else should I try to mock the getter properly and without errors.
