Remove as unknown as DatabaseManager
Unfortunately `Object.defineProperty` doesn't work on proxies, so I've added an options object to `mockedObject` which allows passing in methods that will return a value for a specific property.
This commit is contained in:
@@ -59,18 +59,20 @@ describe("test-adapter", () => {
|
||||
setCurrentDatabaseItemSpy.mockResolvedValue(undefined);
|
||||
resolveQlpacksSpy.mockResolvedValue({});
|
||||
resolveTestsSpy.mockResolvedValue([]);
|
||||
fakeDatabaseManager = {
|
||||
openDatabase: openDatabaseSpy,
|
||||
removeDatabaseItem: removeDatabaseItemSpy,
|
||||
renameDatabaseItem: renameDatabaseItemSpy,
|
||||
setCurrentDatabaseItem: setCurrentDatabaseItemSpy,
|
||||
} as unknown as DatabaseManager;
|
||||
Object.defineProperty(fakeDatabaseManager, "currentDatabaseItem", {
|
||||
get: () => currentDatabaseItem,
|
||||
});
|
||||
Object.defineProperty(fakeDatabaseManager, "databaseItems", {
|
||||
get: () => databaseItems,
|
||||
});
|
||||
fakeDatabaseManager = mockedObject<DatabaseManager>(
|
||||
{
|
||||
openDatabase: openDatabaseSpy,
|
||||
removeDatabaseItem: removeDatabaseItemSpy,
|
||||
renameDatabaseItem: renameDatabaseItemSpy,
|
||||
setCurrentDatabaseItem: setCurrentDatabaseItemSpy,
|
||||
},
|
||||
{
|
||||
dynamicProperties: {
|
||||
currentDatabaseItem: () => currentDatabaseItem,
|
||||
databaseItems: () => databaseItems,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
jest.spyOn(preTestDatabaseItem, "isAffectedByTest").mockResolvedValue(true);
|
||||
|
||||
|
||||
@@ -4,12 +4,32 @@ export type DeepPartial<T> = T extends object
|
||||
}
|
||||
: T;
|
||||
|
||||
export function mockedObject<T extends object>(props: DeepPartial<T>): T {
|
||||
export type DynamicProperties<T extends object> = {
|
||||
[P in keyof T]?: () => T[P];
|
||||
};
|
||||
|
||||
type MockedObjectOptions<T extends object> = {
|
||||
/**
|
||||
* Properties for which the given method should be called when accessed.
|
||||
* The method should return the value to be returned when the property is accessed.
|
||||
* Methods which are explicitly defined in `methods` will take precedence over
|
||||
* dynamic properties.
|
||||
*/
|
||||
dynamicProperties?: DynamicProperties<T>;
|
||||
};
|
||||
|
||||
export function mockedObject<T extends object>(
|
||||
props: DeepPartial<T>,
|
||||
{ dynamicProperties }: MockedObjectOptions<T> = {},
|
||||
): T {
|
||||
return new Proxy<T>({} as unknown as T, {
|
||||
get: (_target, prop) => {
|
||||
if (prop in props) {
|
||||
return (props as any)[prop];
|
||||
}
|
||||
if (dynamicProperties && prop in dynamicProperties) {
|
||||
return (dynamicProperties as any)[prop]();
|
||||
}
|
||||
throw new Error(`Method ${String(prop)} not mocked`);
|
||||
},
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user