Debian Codegraph @

yaml-types/src/function.test.ts

raw
1 import { test } from 'tap'
2 import { parse, parseDocument, stringify } from 'yaml'
3
4 import { functionTag } from '.'
5
6 test('parse valid', t => {
7 const res: Function = parse(
8 `!function |-
9 "foo"
10 () => 'bar'
11 `,
12 { customTags: [functionTag] }
13 )
14 t.type(res, 'function')
15 t.equal(res.toString(), `() => 'bar'`)
16 t.equal(res.name, 'foo')
17 t.equal(res(), undefined, 'does not actually run the code specified')
18 t.end()
19 })
20
21 test('parse invalid name serialization', t => {
22 const doc = parseDocument(
23 `!function |-
24 name: "invalid
25 blah
26 `,
27 { customTags: [functionTag] }
28 )
29 t.has(doc.errors, { length: 1, 0: { code: 'TAG_RESOLVE_FAILED' } })
30 t.end()
31 })
32
33 function foo() {
34 return 1
35 }
36 test('stringify', t => {
37 const res = stringify(foo, { customTags: [functionTag] })
38 // the divergent toString is because typescript parses this test
39 // prior to executing it, and it outputs JS with 4-space indentation
40 // and extraneous semicolons.
41 t.equal(
42 res,
43 `!function |-
44 "foo"
45 function foo() {
46 return 1;
47 }
48 `
49 )
50 t.end()
51 })
52
53 test('unnamed function', t => {
54 // it's actually kind of tricky to get a function that V8 won't
55 // assign *some* sort of intelligible name to. It has to never be
56 // assigned to any variable, or directly pass as an argument to
57 // a named function at its point of creation, hence this line noise.
58 const res = stringify((() => () => {})(), { customTags: [functionTag] })
59 t.equal(
60 res,
61 `!function |-
62 ""
63 () => { }
64 `
65 )
66 t.end()
67 })
68
69 test('parse completely empty value', t => {
70 const src = `!function |-\n`
71 const res: Function = parse(src, { customTags: [functionTag] })
72 t.type(res, 'function')
73 t.equal(res.name, undefined)
74 t.equal(res(), undefined)
75 t.end()
76 })
77
78 class Foo extends Boolean {}
79 test('stringify a class', t => {
80 const res = stringify(Foo, { customTags: [functionTag] })
81 // don't test the actual class body, because that will break
82 // if/when TypeScript is updated.
83 t.ok(
84 res.startsWith(`!function |-
85 "Foo"
86 class Foo extends Boolean {`),
87 'shows class toString value'
88 )
89 t.end()
90 })