So I'm updating dependencies on my project and I've run into a snag...
My unit tests were working perfectly with the below stub. However in the latest version of UUID, this seemingly has broken. Any suggestions on how to fix it?
These are simplistic extracts from the code to illustrate the method I'm using to stub the functionality of uuid and how I am using uuid in my code.
import * as uuid from 'uuid'
sinon.stub(uuid, 'v4').returns('some-v4-uuid')
import * as uuid from 'uuid'
const payload = {
id: uuid.v4()
}
The dependency versions
Here is the code
Here is the test
Given the uuid@7
dist uses Object.defineProperty
to export the versions, I don't think stubbing is possible. This is annoying but you might have to put an abstraction layer on top of uuid and stub that function.
Crediting Oriol:
// monkey-patch Object.defineProperty to allow the method to be configurable before importing uuid:
const _defineProperty = Object.defineProperty;
let _v4;
Object.defineProperty = function(obj, prop, descriptor) {
if (prop == 'v4') {
descriptor.configurable = true;
if (!_v4) { _v4 = descriptor.value; }
}
return _defineProperty(obj, prop, descriptor);
};
import * as uuid from 'uuid';
// Initialise your desired UUIDs
const uuids = [
'c23624e9-e21d-4f19-8853-cfca73e7109a',
'804759ea-d5d2-4b30-b79d-98dd4bfaf053',
'7aa53488-ad43-4467-aa3d-a97fc3bc90b8'
];
// stub it yourself
Object.defineProperty(uuid, 'v4', { value: () => uuids.shift() });
// and then if you need to restore:
Object.defineProperty(uuid, 'v4', { value: _v4 });
Object.defineProperty = _defineProperty;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With