Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: makeApiContextWrapper and createMockProxy #1312

Merged
merged 6 commits into from
May 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 88 additions & 0 deletions packages/utils/src/MockProxy.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import createMockProxy, { MockProxySymbol } from './MockProxy';

describe('createMockProxy', () => {
it('should proxy property access as jest.fn() unless explicitly set', () => {
const mock = createMockProxy<Record<string, unknown>>({
name: 'mock.name',
});

expect(mock.name).toEqual('mock.name');
expect(mock.propA).toBeInstanceOf(jest.fn().constructor);
expect(mock.propB).toBeInstanceOf(jest.fn().constructor);
});

it('should not interfere with `await` by not proxying `then` property', async () => {
const mock = createMockProxy<Record<string, unknown>>({});
expect(mock.then).toBeUndefined();

const result = await mock;

expect(result).toBe(mock);
});

it('should only show `in` for explicit properties', () => {
const mock = createMockProxy<Record<string, unknown>>({
name: 'mock.name',
age: 42,
});

expect('name' in mock).toBeTruthy();
expect('age' in mock).toBeTruthy();
expect('blah' in mock).toBeFalsy();
});

it.each([
Symbol.iterator,
'then',
'asymmetricMatch',
'hasAttribute',
'nodeType',
'ref',
'tagName',
'toJSON',
])('should return undefined for default props', prop => {
const mock = createMockProxy();

// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((mock as any)[prop]).toBeUndefined();
});

it('should return custom Symbol.toStringTag', () => {
const mock = createMockProxy();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((mock as any)[Symbol.toStringTag]).toEqual('Mock Proxy');
});

it('should return internal storage by name', () => {
const overrides = {
name: 'mock.name',
age: 42,
};

const mock = createMockProxy<{
name: string;
age: number;
testMethod: () => void;
}>(overrides);

mock.testMethod();

expect(mock[MockProxySymbol.defaultProps]).toEqual({
then: undefined,
asymmetricMatch: undefined,
hasAttribute: undefined,
nodeType: undefined,
ref: undefined,
tagName: undefined,
toJSON: undefined,
[Symbol.iterator]: undefined,
});

expect(mock[MockProxySymbol.overrides]).toEqual(overrides);

expect(mock[MockProxySymbol.proxies]).toEqual({
testMethod: expect.any(Function),
});
expect(mock.testMethod).toBeInstanceOf(jest.fn().constructor);
});
});
96 changes: 96 additions & 0 deletions packages/utils/src/MockProxy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
const defaultPropsSymbol: unique symbol = Symbol('mockProxyDefaultProps');
const overridesSymbol: unique symbol = Symbol('mockProxyOverrides');
const proxiesSymbol: unique symbol = Symbol('mockProxyProxies');

export const MockProxySymbol = {
defaultProps: defaultPropsSymbol,
overrides: overridesSymbol,
proxies: proxiesSymbol,
} as const;

// Set default values on certain properties so they don't get automatically
// proxied as jest.fn() instances.
const mockProxyDefaultProps = {
// `Symbol.iterator` - returning a jest.fn() throws a TypeError
// `then` - avoid issues with `await` treating object as "thenable"
[Symbol.iterator]: undefined,
then: undefined,
// Jest makes calls to `asymmetricMatch`, `hasAttribute`, `nodeType`
// `tagName`, and `toJSON`. react-test-renderer checks `ref`
asymmetricMatch: undefined,
ref: undefined,
hasAttribute: undefined,
nodeType: undefined,
tagName: undefined,
toJSON: undefined,
};

/**
* The proxy target contains state + configuration for the proxy
*/
export interface MockProxyTarget<T> {
[MockProxySymbol.defaultProps]: typeof mockProxyDefaultProps;
[MockProxySymbol.overrides]: Partial<T>;
[MockProxySymbol.proxies]: Record<keyof T, jest.Mock>;
}

/**
* Creates a mock object for a type `T` using a Proxy object. Each prop can
* optionally be set via the constructor. Any prop that is not set will be set
* to a jest.fn() instance on first access with the exeption of "then" which
* will not be automatically proxied.
* @param overrides Optional props to explicitly set on the Proxy.
* @returns
*/
export default function createMockProxy<T>(
overrides: Partial<T> = {}
): T & MockProxyTarget<T> {
const targetDef: MockProxyTarget<T> = {
[MockProxySymbol.defaultProps]: mockProxyDefaultProps,
[MockProxySymbol.overrides]: overrides,
[MockProxySymbol.proxies]: {} as Record<keyof T, jest.Mock>,
};

return new Proxy(targetDef, {
get(target, name) {
if (name === Symbol.toStringTag) {
return 'Mock Proxy';
}

// Reserved attributes for the proxy
if (
MockProxySymbol.defaultProps === name ||
MockProxySymbol.overrides === name ||
MockProxySymbol.proxies === name
) {
return target[name as keyof typeof target];
}

// Properties that have been explicitly overriden
if (name in target[MockProxySymbol.overrides]) {
return target[MockProxySymbol.overrides][name as keyof Partial<T>];
}

// Properties that have defaults set
if (name in target[MockProxySymbol.defaultProps]) {
return target[MockProxySymbol.defaultProps][
name as keyof typeof mockProxyDefaultProps
];
}

// Any other property access will create and cache a jest.fn() instance
if (target[MockProxySymbol.proxies][name as keyof T] == null) {
// eslint-disable-next-line no-param-reassign
target[MockProxySymbol.proxies][name as keyof T] = jest
.fn()
.mockName(String(name));
}

return target[MockProxySymbol.proxies][name as keyof T];
},
// Only consider explicitly defined props as "in" the proxy
has(target, name) {
return name in target[MockProxySymbol.overrides];
},
}) as T & typeof targetDef;
}
31 changes: 2 additions & 29 deletions packages/utils/src/TestUtils.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';

import TestUtils from './TestUtils';
import createMockProxy from './MockProxy';

beforeEach(() => {
jest.clearAllMocks();
Expand Down Expand Up @@ -150,35 +151,7 @@ describe('click', () => {
});

describe('createMockProxy', () => {
it('should proxy property access as jest.fn() unless explicitly set', () => {
const mock = TestUtils.createMockProxy<Record<string, unknown>>({
name: 'mock.name',
});

expect(mock.name).toEqual('mock.name');
expect(mock.propA).toBeInstanceOf(jest.fn().constructor);
expect(mock.propB).toBeInstanceOf(jest.fn().constructor);
});

it('should not interfere with `await` by not proxying `then` property', async () => {
const mock = TestUtils.createMockProxy<Record<string, unknown>>({});
expect(mock.then).toBeUndefined();

const result = await mock;

expect(result).toBe(mock);
});

it('should only show `in` for explicit properties', () => {
const mock = TestUtils.createMockProxy<Record<string, unknown>>({
name: 'mock.name',
age: 42,
});

expect('name' in mock).toBeTruthy();
expect('age' in mock).toBeTruthy();
expect('blah' in mock).toBeFalsy();
});
expect(TestUtils.createMockProxy).toBe(createMockProxy);
});

describe('extractCallArgs', () => {
Expand Down
38 changes: 3 additions & 35 deletions packages/utils/src/TestUtils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type userEvent from '@testing-library/user-event';
import createMockProxy from './MockProxy';

interface MockContext {
arc: jest.Mock<void>;
Expand Down Expand Up @@ -179,42 +180,9 @@ class TestUtils {
* optionally be set via the constructor. Any prop that is not set will be set
* to a jest.fn() instance on first access with the exeption of "then" which
* will not be automatically proxied.
* @param props Optional props to explicitly set on the Proxy.
* @returns
* @param overrides Optional props to explicitly set on the Proxy.
*/
static createMockProxy<T>(props: Partial<T> = {}): T {
return new Proxy(
{
props: {
// Disable auto-proxying of certain properties that cause trouble.
// - Symbol.iterator - returning a jest.fn() throws a TypeError
// - then - avoid issues with `await` treating object as "thenable"
[Symbol.iterator]: undefined,
then: undefined,
...props,
},
proxies: {} as Record<keyof T, jest.Mock>,
},
{
get(target, name) {
if (name in target.props) {
return target.props[name as keyof T];
}

if (target.proxies[name as keyof T] == null) {
// eslint-disable-next-line no-param-reassign
target.proxies[name as keyof T] = jest.fn();
}

return target.proxies[name as keyof T];
},
// Only consider explicitly defined props as "in" the proxy
has(target, name) {
return name in target.props;
},
}
) as T;
}
static createMockProxy = createMockProxy;

/**
* Attempt to extract the args for the nth call to a given function. This will
Expand Down