Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

I've been unable to get my test jasmine test suite running with webpack 4. After upgrading webpack, I get the following error for almost every test:

Error: <spyOn> : getField is not declared writable or has no setter 

This is due to a common pattern we use to create spys for simple functions is:

import * as mod from 'my/module';
//...
const funcSpy = spyOn(mod, 'myFunc');

I've played around with module.rules[].type but none of the options seem to do the trick.

This webpack GH issue indicates ECMA modules are meant to not be writable which makes sense for the web but is there really no workaround for testing?

Relevant package versions:

"jasmine-core": "2.6.4",
"typescript": "2.5.3",
"webpack": "4.1.1",
"webpack-cli": "^2.0.12",
"karma": "^0.13.22",
"karma-jasmine": "^1.1.0",
"karma-webpack": "^2.0.13",
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...