2019-08-15 15:52:36 +08:00
|
|
|
const __NULL__ = { notExist: true };
|
|
|
|
|
2019-05-06 12:04:39 +08:00
|
|
|
export function spyElementPrototypes(Element, properties) {
|
|
|
|
const propNames = Object.keys(properties);
|
|
|
|
const originDescriptors = {};
|
|
|
|
|
|
|
|
propNames.forEach(propName => {
|
|
|
|
const originDescriptor = Object.getOwnPropertyDescriptor(Element.prototype, propName);
|
2019-08-15 15:52:36 +08:00
|
|
|
originDescriptors[propName] = originDescriptor || __NULL__;
|
2019-05-06 12:04:39 +08:00
|
|
|
|
|
|
|
const spyProp = properties[propName];
|
|
|
|
|
|
|
|
if (typeof spyProp === 'function') {
|
|
|
|
// If is a function
|
|
|
|
Element.prototype[propName] = function spyFunc(...args) {
|
|
|
|
return spyProp.call(this, originDescriptor, ...args);
|
|
|
|
};
|
|
|
|
} else {
|
|
|
|
// Otherwise tread as a property
|
|
|
|
Object.defineProperty(Element.prototype, propName, {
|
|
|
|
...spyProp,
|
|
|
|
set(value) {
|
|
|
|
if (spyProp.set) {
|
|
|
|
return spyProp.set.call(this, originDescriptor, value);
|
|
|
|
}
|
|
|
|
return originDescriptor.set(value);
|
|
|
|
},
|
|
|
|
get() {
|
|
|
|
if (spyProp.get) {
|
|
|
|
return spyProp.get.call(this, originDescriptor);
|
|
|
|
}
|
|
|
|
return originDescriptor.get();
|
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
return {
|
|
|
|
mockRestore() {
|
|
|
|
propNames.forEach(propName => {
|
|
|
|
const originDescriptor = originDescriptors[propName];
|
2019-08-15 15:52:36 +08:00
|
|
|
if (originDescriptor === __NULL__) {
|
|
|
|
delete Element.prototype[propName];
|
|
|
|
} else if (typeof originDescriptor === 'function') {
|
2019-05-06 12:04:39 +08:00
|
|
|
Element.prototype[propName] = originDescriptor;
|
|
|
|
} else {
|
|
|
|
Object.defineProperty(Element.prototype, propName, originDescriptor);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
},
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
export function spyElementPrototype(Element, propName, property) {
|
|
|
|
return spyElementPrototypes(Element, {
|
|
|
|
[propName]: property,
|
|
|
|
});
|
|
|
|
}
|