You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
72 lines
2.0 KiB
72 lines
2.0 KiB
5 years ago
|
const __NULL__ = { notExist: true };
|
||
|
|
||
5 years ago
|
type ElementType<P> = {
|
||
|
prototype: P;
|
||
|
};
|
||
|
|
||
|
export function spyElementPrototypes<P extends {}>(Element: ElementType<P>, properties: P) {
|
||
6 years ago
|
const propNames = Object.keys(properties);
|
||
|
const originDescriptors = {};
|
||
|
|
||
|
propNames.forEach(propName => {
|
||
|
const originDescriptor = Object.getOwnPropertyDescriptor(Element.prototype, propName);
|
||
5 years ago
|
originDescriptors[propName] = originDescriptor || __NULL__;
|
||
6 years ago
|
|
||
|
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];
|
||
5 years ago
|
if (originDescriptor === __NULL__) {
|
||
|
delete Element.prototype[propName];
|
||
|
} else if (typeof originDescriptor === 'function') {
|
||
6 years ago
|
Element.prototype[propName] = originDescriptor;
|
||
|
} else {
|
||
|
Object.defineProperty(Element.prototype, propName, originDescriptor);
|
||
|
}
|
||
|
});
|
||
|
},
|
||
|
};
|
||
|
}
|
||
|
|
||
5 years ago
|
type FunctionPropertyNames<T> = {
|
||
|
[K in keyof T]: T[K] extends (...args: any[]) => any ? K : never;
|
||
|
}[keyof T] &
|
||
|
string;
|
||
|
|
||
|
export function spyElementPrototype<P extends {}, K extends FunctionPropertyNames<P>>(
|
||
|
Element: ElementType<P>,
|
||
|
propName: K,
|
||
|
property: P[K],
|
||
|
) {
|
||
6 years ago
|
return spyElementPrototypes(Element, {
|
||
|
[propName]: property,
|
||
|
});
|
||
|
}
|