用 sinon 存根 uuid

Stubbing uuid with sinon

所以我正在更新我的项目的依赖项,但我 运行 遇到了麻烦...

我的单元测试与下面的存根完美配合。然而在最新版本的 UUID 中,这似乎已经被打破了。关于如何修复它有什么建议吗?

这些是代码的简单摘录,用于说明我用来存根 uuid 功能的方法以及我如何在我的代码中使用 uuid。

import * as uuid from 'uuid'

sinon.stub(uuid, 'v4').returns('some-v4-uuid')
import * as uuid from 'uuid'

const payload = {
  id: uuid.v4()
}

依赖版本

Here is the code

Here is the test

鉴于 uuid@7 dist 使用 Object.defineProperty 导出版本,我不认为 stubbing is possible。这很烦人,但您可能必须在 uuid 之上放置一个抽象层并存根该函数。

记入

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

您可以创建一个新文件 (uuid.js) 并按此操作

// uuid.js
const uuid = require('uuid');
    
const v4 = () => uuid.v4();
    
module.exports = { v4 };

// testcase
const uuid = require('uuid.js');//This isn't the actual npm library
const sinon = require('sinon');

describe('request beta access API', () => {
const sandbox = sinon.createSandbox();
    
sandbox.mock(uuid).expects('v4')
 .returns('some-v4-uuid');
    
 //Testcases
    
});