fix: jsonValue() type is generic (#6865)

During the migration to TS we changed `jsonValue` so it returned
`<Record<string, unknown>>`. This is only true if all the JSON values it
returns are objects; but it could return an array, a string, a number,
etc. Therefore we make the type generic, setting the default to
`unknown`, so the user has control over the type.
This commit is contained in:
Jack Franklin 2021-02-11 09:50:15 +00:00 committed by GitHub
parent 63d48b2ecb
commit bdaba7829d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 22 additions and 5 deletions

View File

@ -243,7 +243,7 @@ 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; }',
@ -251,9 +251,9 @@ export class JSHandle {
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;
}
/**

View File

@ -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) => {

View File

@ -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();