Skip to content

Commit

Permalink
Throw more helpful error when setting Pair.commentBefore incorrectly (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
eemeli committed Apr 26, 2020
1 parent 1facc1b commit ed53620
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
9 changes: 7 additions & 2 deletions src/schema/Pair.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
32 changes: 32 additions & 0 deletions tests/doc/comments.js
Original file line number Diff line number Diff line change
@@ -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', () => {
Expand Down Expand Up @@ -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/)
})
})

0 comments on commit ed53620

Please sign in to comment.