How do you mock process.platform using jasmine specs?
1 Answer
You can use Object.defineProperty()
to set value of process.platform
in beforeAll
and then reset it to original in afterAll
after tests are finished.
If you print of Object.getOwnPropertyDescriptor(process, "platform")
to get descriptor
configuration of platform.process
in node.js console then you will get following:
{ value: 'darwin',
writable: false,
enumerable: true,
configurable: true }
As you can see, value of process.platform
is not writable (see docs for more information) so you can't set it using assignment operator. but you can override it using Object.defineProperty
.
Jasmine Example
describe('test process platform', function(){
beforeAll(function(){
this.originalPlatform = process.platform;
Object.defineProperty(process, 'platform', {
value: 'MockOS'
});
});
it(/*test*/);
....
it(/*test*/);
afterAll(function(){
Object.defineProperty(process, 'platform', {
value: this.originalPlatform
});
});
});
-
Thank you so much, especially for the thorough explanation through
getOwnPropertyDescriptor
! I'm also having an issue with mocking path.sep / path.separator, even though it's writeable. Any ideas there? May 22, 2015 at 21:45 -
if
path.sep
is writable then you can simply set it using assignment operatorpath.sep = '#'
. i am able to do it on my machine. May 22, 2015 at 22:03 -
Note: For some reason something like this has stopped working for me recently, but this still works. Thanks jad-panda :) Feb 25, 2018 at 11:28
-
This does not work for me using node20:
TypeError: Cannot redefine property: platform
Oct 12 at 0:40