diff --git a/src/schema/Pair.js b/src/schema/Pair.js index 3d2aa576..13a7e581 100644 --- a/src/schema/Pair.js +++ b/src/schema/Pair.js @@ -37,12 +37,17 @@ export class Pair extends Node { } get commentBefore() { - return this.key && this.key.commentBefore + return this.key instanceof Node ? this.key.commentBefore : undefined } set commentBefore(cb) { if (this.key == null) this.key = new Scalar(null) - this.key.commentBefore = cb + if (this.key instanceof Node) this.key.commentBefore = cb + else { + const msg = + 'Pair.commentBefore is an alias for Pair.key.commentBefore. To set it, the key must be a Node.' + throw new Error(msg) + } } addToJSMap(ctx, map) { diff --git a/tests/doc/comments.js b/tests/doc/comments.js index cc84b42e..cbcb3353 100644 --- a/tests/doc/comments.js +++ b/tests/doc/comments.js @@ -1,5 +1,6 @@ import { source } from 'common-tags' import { YAML } from '../../src/index' +import { Pair } from '../../src/schema/Pair' describe('parse comments', () => { describe('body', () => { @@ -840,3 +841,34 @@ a: expect(String(doc)).toBe(src) }) }) + +describe('Pair.commentBefore', () => { + test('Should get key comment', () => { + const key = YAML.createNode('foo', true) + const pair = new Pair(key, 42) + key.commentBefore = 'cc' + expect(pair.commentBefore).toBe('cc') + }) + + test('Should set key comment', () => { + const key = YAML.createNode('foo', true) + const pair = new Pair(key, 42) + pair.commentBefore = 'cc' + expect(key.commentBefore).toBe('cc') + }) + + test('Should create a key from a null value', () => { + const pair = new Pair(null, 42) + expect(pair.key).toBeNull() + pair.commentBefore = 'cc' + expect(pair.key).not.toBeNull() + expect(pair.key.commentBefore).toBe('cc') + }) + + test('Should throw for non-Node key', () => { + const pair = new Pair({ foo: 'bar' }, 42) + expect(() => { + pair.commentBefore = 'cc' + }).toThrow(/commentBefore is an alias/) + }) +})