Search code examples
angularjasminekarma-runner

Karma: property does not have access type get


I have an error in my Karma tests in my Angular application. The error is when I run my tests:

Failed: Property activePropertyChanged does not have access type get

I'm trying to mock a service called ModuleSpecService. In this service there's the following getter:

get activePropertyChanged(): Observable<SpecificationPropertyObject> {
    return this.activePropChangedSubject.asObservable();
}

And in my spec file I mock it like this:

spyOnProperty(moduleSpecServiceMock, 'activePropertyChanged', 'get').and.returnValue(of());

// then, in configureTestingModule() I define/mock the service like this:
providers: [{ provide: ModuleSpecService, useValue: moduleSpecServiceMock }]

So there's clearly a getter in my service which I want to mock. If I remove the line with spyOnProperty() it throws the following error:

TypeError: this.moduleSpecService.activePropertyChanged.subscribe is not a function

so I definitely need the mock.

Any idea what could go wrong?


Solution

  • Since this seems to be a bug in jasmine I managed to fix this with a workaround:

    Instead of this:

    spyOnProperty(moduleSpecServiceMock, 'activePropertyChanged', 'get').and.returnValue(of()); 
    

    I defined the property like this:

    (moduleSpecServiceMock as any).activePropertyChanged = of();
    

    I had to cast it as any, because if not, it (correctly) told me that activePropertyChange is a read-only property (since it has only a getter).

    Not the best solution, but at least it works :)