ts-mock-imports: Cannot set property x of [object Module] which has only a getter
Error
debug.js:21 TypeError: Cannot set property AnalyticsService of [object Module] which has only a getter
at <Jasmine>
at new MockManager (mock-manager.js:26)
at Function.push../node_modules/ts-mock-imports/lib/import-mock.js.ImportMock.mockClass (import-mock.js:15)
at UserContext.<anonymous> (fbdb-requests.service.spec.ts:54)
at ZoneDelegate.invoke (zone-evergreen.js:359)
at ProxyZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke (zone-testing.js:308)
at ZoneDelegate.invoke (zone-evergreen.js:358)
at Zone.run (zone-evergreen.js:124)
at runInTestZone (zone-testing.js:561)
at UserContext.<anonymous> (zone-testing.js:576)
at <Jasmine>
Minimal code
import { ImportMock } from 'ts-mock-imports';
import * as analyticsModule from 'services/AnalyticsService';
analyticsServiceMock = ImportMock.mockClass(analyticsModule, 'AnalyticsService');
It’s that mock call that mockClass call that blows up. Similarly blows up with mockOther.
Cut down module attempted to be mocked
import * as utils from "utils";
//in the future this should subscribe to the various state services, plan, project, user, etc
// for now? leach off the old analytics service
export class AnalyticsService{
private globals = {}
multiselect(){ ... }
}
export let analyticsService = new AnalyticsService();
window.analyticsService = analyticsService;
Other things of note
- build: angular-cli v8
- testing framework: jasmine 3.4
Near as I’ve been able to tell, you’re unable to mock es6 imports because they’re supposed to be readonly. Which is roughly what the above illustrates. But I figured this package figured out some way around that limitation.
About this issue
- Original URL
- State: closed
- Created 4 years ago
- Comments: 22 (6 by maintainers)
The solution that worked for me is this one:
I had a module exporting a static function:
and I use to mock it like this:
and I changed it to this:
effectively not using ts-mock-imports for static functions exported in external modules…
Hi, it seems like this issue and the limitations that come with TS 3.9 should be at the top of the readme, in large text – otherwise this risks wasting a lot of developer time. 🙏
Hit this issue as well, thought I was going mad when my mocks stopped working! @EmandM do you think you’ll be able to work around this issue? Would be great to have a solution that doesn’t require adding other tweaks to all our projects using
ts-mock-imports😃@EmandM Could you please add a warning to the Readme about this gotcha? I got bitten by this today and spent half a day bashing my head against the desk trying to figure out why on earth my mocks are no longer doing a thing 😦. (Ranting aside: I really love this library, thanks for creating it! It really hurts to use dependency injection instead…)