From aa0a1d445668df7aa4bcafaf6bdf8811312ed713 Mon Sep 17 00:00:00 2001 From: Eemeli Aro Date: Tue, 4 Apr 2023 15:50:02 +0300 Subject: [PATCH] fix: Improve missing-argument error on node .toJS() method (#458) --- src/nodes/Node.ts | 3 ++- tests/node-to-js.ts | 5 +++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/nodes/Node.ts b/src/nodes/Node.ts index 829d20b7..00595a2b 100644 --- a/src/nodes/Node.ts +++ b/src/nodes/Node.ts @@ -4,7 +4,7 @@ import type { ToJSOptions } from '../options.js' import { Token } from '../parse/cst.js' import type { StringifyContext } from '../stringify/stringify.js' import type { Alias } from './Alias.js' -import { NODE_TYPE } from './identity.js' +import { isDocument, NODE_TYPE } from './identity.js' import type { Scalar } from './Scalar.js' import { toJS, ToJSContext } from './toJS.js' import type { YAMLMap } from './YAMLMap.js' @@ -97,6 +97,7 @@ export abstract class NodeBase { doc: Document, { mapAsMap, maxAliasCount, onAnchor, reviver }: ToJSOptions = {} ): any { + if (!isDocument(doc)) throw new TypeError('A document argument is required') const ctx: ToJSContext = { anchors: new Map(), doc, diff --git a/tests/node-to-js.ts b/tests/node-to-js.ts index 41beed96..552ce3a4 100644 --- a/tests/node-to-js.ts +++ b/tests/node-to-js.ts @@ -63,6 +63,11 @@ describe('alias', () => { }) describe('options', () => { + test('doc is required', () => { + const doc = parseDocument('key: 42') + expect(() => doc.contents?.toJS({} as any)).toThrow(TypeError) + }) + test('mapAsMap', () => { const doc = parseDocument('key: 42') expect(doc.contents?.toJS(doc, { mapAsMap: true })).toMatchObject(