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

chore(ct): throw error when props are not json serializable #22025

Merged
merged 3 commits into from
Mar 29, 2023
Merged
Changes from 1 commit
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
20 changes: 20 additions & 0 deletions packages/playwright-test/src/mount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ export const fixtures: Fixtures<

mount: async ({ page }, use) => {
await use(async (component: JsxComponent | string, options?: MountOptions) => {
if (options?.props && !isJson(options.props))
throw new Error('The mount function props are not JSON serializable.');
const selector = await (page as any)._wrapApiCall(async () => {
return await innerMount(page, component, options);
}, true);
Expand All @@ -72,6 +74,24 @@ export const fixtures: Fixtures<
},
};

const jsonType: Record<string, Function> = {
string: (value: any) => typeof value === 'string',
number: (value: any) => typeof value === 'number',
boolean: (value: any) => typeof value === 'boolean',
null: (value: any) => value === null,
array: (value: any) => Array.isArray(value) && value.every(isJson),
object: (value: any) => typeof value === 'object' && value !== null && !Array.isArray(value)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

JSON will have a default serializing conventions for types like Date, but I guess it is Ok to be more restrictive here.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure if i fully get that. Thought only the string, number, boolean, null, array and object types are JSON serializable? Do you mean that JSON.parse(JSON.stringify({ boop: Date })) will return {} ?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Look at what JSON.stringify({ data: new Date() }) produces, but don't bother.

&& Object.values(value).every(isJson),
}

function isJson(value: any): boolean {
const valueType = Array.isArray(value) ? 'array' : typeof value;
const validate = jsonType[valueType];
if (validate)
return validate(value);
return false;
}

function isJsxApi(options: Record<string, unknown>): options is JsxComponent {
return options?.kind === 'jsx';
}
Expand Down