Can webpack 4 modules be configured as to allow Jasmine to spy on their members? Can webpack 4 modules be configured as to allow Jasmine to spy on their members? typescript typescript

Can webpack 4 modules be configured as to allow Jasmine to spy on their members?


There's spyOnProperty which allows treating a property as read-only by setting the accessType argument to 'get'.

Your setup would then look like

import * as mod from 'my/module';//...const funcSpy = jasmine.createSpy('myFunc').and.returnValue('myMockReturnValue');spyOnProperty(mod, 'myFunc', 'get').and.returnValue(funcSpy);


Adding to @Anton Poznyakovskiy's answer:

I've added this TypeScript function to my shared testing module as a convenience:

export const spyOnFunction = <T>(obj: T, func: keyof T) => {  const spy = jasmine.createSpy(func as string);  spyOnProperty(obj, func, 'get').and.returnValue(spy);  return spy;};

Example usage:

import * as mod from 'my/module';//...spyOnFunction(mod, 'myFunc').and.returnValue('myMockReturnValue');


There's this GitHub issue where they arrive at the same conclusion; that immutable exports are intended. But user lavelle has a workaround (in this comment) where they've created different webpack configs for test and production code. The test config uses "commonjs" modules, which seems to have worked for them by not creating getters.