|
| 1 | +// @file jest helper file |
| 2 | +const fs = require('fs'); |
| 3 | +const path = require('path'); |
| 4 | +const prettier = require('prettier'); |
| 5 | + |
| 6 | +function mergeDefaultOptions(parserConfig) { |
| 7 | + return { |
| 8 | + plugins: [path.dirname(__dirname)], |
| 9 | + printWidth: 80, |
| 10 | + ...parserConfig |
| 11 | + }; |
| 12 | +} |
| 13 | + |
| 14 | +function prettyprint(src, options) { |
| 15 | + const result = prettier.formatWithCursor(src, options); |
| 16 | + if (options.cursorOffset >= 0) { |
| 17 | + result.formatted = `${result.formatted.slice( |
| 18 | + 0, |
| 19 | + result.cursorOffset |
| 20 | + )}<|>${result.formatted.slice(result.cursorOffset)}`; |
| 21 | + } |
| 22 | + return result.formatted; |
| 23 | +} |
| 24 | + |
| 25 | +/** |
| 26 | + * Wraps a string in a marker object that is used by `./raw-serializer.js` to |
| 27 | + * directly print that string in a snapshot without escaping all double quotes. |
| 28 | + * Backticks will still be escaped. |
| 29 | + */ |
| 30 | +function raw(string) { |
| 31 | + if (typeof string !== 'string') { |
| 32 | + throw new Error('Raw snapshots have to be strings.'); |
| 33 | + } |
| 34 | + return { [Symbol.for('raw')]: string }; |
| 35 | +} |
| 36 | + |
| 37 | +function read(filename) { |
| 38 | + return fs.readFileSync(filename, 'utf8'); |
| 39 | +} |
| 40 | + |
| 41 | +function parse(string, opts) { |
| 42 | + return prettier.__debug.parse(string, opts, /* massage */ true).ast; |
| 43 | +} |
| 44 | + |
| 45 | +module.exports = { mergeDefaultOptions, parse, prettyprint, raw, read }; |
0 commit comments