Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stubbing uuid with sinon

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

  • "uuid": "7.0.1"
  • "sinon": "9.0.0"

Here is the code

Here is the test

like image 783
Skaleb Avatar asked Feb 26 '20 15:02

Skaleb


2 Answers

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.

like image 55
kierans Avatar answered Nov 17 '22 04:11

kierans


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;
like image 29
Nicholas Albion Avatar answered Nov 17 '22 03:11

Nicholas Albion