[英]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()
}
依赖版本
鉴于uuid@7
dist 使用Object.defineProperty
来导出版本,我认为不可能存根。 这很烦人,但您可能必须在 uuid 之上放置一个抽象层并存根该函数。
归功于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;
您可以创建一个新文件(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
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.