Despite referring to this Stack Overflow post, it doesn't seem to be relevant to my situation.
In my scenario, I have a service named AnimationService
, which relies on another service called AnimationStateService
. The AnimationStateService
contains a getter method called state
that I want to mock in my test case. Here is how my test is set up:
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 attempting to mock the getter using:
animationStateService.status.and.returnValue(AnimationStatus.Stopped);
or:
spyOnProperty(animationStateService, "status").and.returnValue(AnimationStatus.Stopped);
It did not work as expected. The getter did not return the value that was set.
This method works:
animationStateService.status = AnimationStatus.Stopped;
however, it triggers a TSLint error:
Cannot assign to 'status' because it is a constant or a read-only property.
Therefore, I am currently unsure of what other approaches I should consider to properly mock the getter without encountering errors.