UNPKG

1.55 kBJavaScriptView Raw
1/*!
2 * Copyright (c) 2015-2017 Cisco Systems, Inc. See LICENSE file.
3 */
4
5import parse from './parse';
6import template from 'babel-template';
7import traverse from 'babel-traverse';
8import generateSpec from './mocha-template';
9
10import {
11 build as buildLiteralAssertion,
12 test as literalAssertionTest
13} from './assertions/literal';
14
15const assertionStatementTemplate = template(`
16 return Promise.resolve(ORIGINAL)
17 .then(function(result) {
18 ASSERTIONS
19 })
20`);
21
22/**
23 * @param {Object} options
24 * @param {ast} options.comment
25 * @param {string} options.name
26 * @param {string} options.filename
27 * @param {string} options.type
28 * @returns {ast}
29 */
30export default function transform({
31 comment, name, filename, type
32}) {
33 const ast = parse(comment);
34
35 traverse(ast, {
36 enter(path) {
37 if (path.node.trailingComments) {
38 const assertions = path.node.trailingComments.map(makeAsserter);
39 if (assertions.length) {
40 Reflect.deleteProperty(path.node, 'trailingComments');
41
42 path.replaceWith(assertionStatementTemplate({
43 ORIGINAL: path.node,
44 ASSERTIONS: assertions
45 }));
46 }
47 }
48 }
49 });
50
51 return generateSpec({
52 testCase: ast,
53 name,
54 filename,
55 type
56 });
57}
58
59/**
60 * Takes a trailing comment from an example block and changes it to an assertion
61 * @param {CommentBlock} comment
62 * @returns {ast}
63 */
64function makeAsserter(comment) {
65 if (literalAssertionTest(comment.value)) {
66 return buildLiteralAssertion(comment.value);
67 }
68
69 return null;
70}