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: jsonValue() type is generic #6865

Merged
merged 3 commits into from Feb 11, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/common/JSHandle.ts
Expand Up @@ -243,17 +243,17 @@ export class JSHandle {
* on the object in page and consequent {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse | JSON.parse} in puppeteer.
* **NOTE** The method throws if the referenced object is not stringifiable.
*/
async jsonValue(): Promise<Record<string, unknown>> {
async jsonValue<T = unknown>(): Promise<T> {
if (this._remoteObject.objectId) {
const response = await this._client.send('Runtime.callFunctionOn', {
functionDeclaration: 'function() { return this; }',
objectId: this._remoteObject.objectId,
returnByValue: true,
awaitPromise: true,
});
return helper.valueFromRemoteObject(response.result);
return helper.valueFromRemoteObject(response.result) as T;
}
return helper.valueFromRemoteObject(this._remoteObject);
return helper.valueFromRemoteObject(this._remoteObject) as T;
}

/**
Expand Down
2 changes: 1 addition & 1 deletion test/evaluation.spec.ts
Expand Up @@ -278,7 +278,7 @@ describe('Evaluation specs', function () {

const windowHandle = await page.evaluateHandle(() => window);
const errorText = await windowHandle
.jsonValue()
.jsonValue<string>()
.catch((error_) => error_.message);
const error = await page
.evaluate<(errorText: string) => Error>((errorText) => {
Expand Down
19 changes: 18 additions & 1 deletion test/jshandle.spec.ts
Expand Up @@ -114,9 +114,26 @@ describe('JSHandle', function () {
const { page } = getTestState();

const aHandle = await page.evaluateHandle(() => ({ foo: 'bar' }));
const json = await aHandle.jsonValue();
const json = await aHandle.jsonValue<Record<string, string>>();
expect(json).toEqual({ foo: 'bar' });
});

it('works with jsonValues that are not objects', async () => {
const { page } = getTestState();

const aHandle = await page.evaluateHandle(() => ['a', 'b']);
const json = await aHandle.jsonValue<string[]>();
expect(json).toEqual(['a', 'b']);
});

it('works with jsonValues that are primitives', async () => {
const { page } = getTestState();

const aHandle = await page.evaluateHandle(() => 'foo');
const json = await aHandle.jsonValue<string>();
expect(json).toEqual('foo');
});

itFailsFirefox('should not work with dates', async () => {
const { page } = getTestState();

Expand Down