@zoroaster/mask

2.7.2 • Public • Published

@zoroaster/mask

npm version Pipeline Badge

@zoroaster/mask is The Code For Zoroaster Mask Testing.

yarn add -D @zoroaster/mask

Table Of Contents

API

The package is available by importing its default function:

import makeTestSuite from '@zoroaster/mask'

makeTestSuite(
  path: (string|!Array<string>),
  config: MaskConfig,
): TestSuite

Creates a new test suite based on the config. The test suite should be exported from JS files, either as a default, or named export.

  • path* (string | !Array<string>): The path to the mask result file or directory. Can also pass an array of paths.
  • config* MaskConfig: Configuration for making test suites.

The exported test suite will be run with Zoroaster Context-Testing Framework. The simplest form of a mask is to use the getResults property, which acts as a template for test cases, which will receive the inputs (e.g., input) from the mask result as properties of the this context, and the contexts via the arguments. The output will be compared to the expected property of the mask.

For example, given the following function:

import read from '@wrote/read'

/**
 * An example function that reads a file.
 * @param {string} path The path to the file to read.
 * @param {string} input The string to prepend.
 */
const fn = async (path, input) => {
  const res = await read(path)
  return `${input}: ${res}`
}

export default fn

Zoroaster can test it using a mask:

Mask Mask Result
/* yarn example/ */
import makeTestSuite from '@zoroaster/mask'
import fn from '../../src'

class Context {
  /**
   * Returns the path to the fixture.
   */
  get fixture() { return 'example/test/fixture/test.txt' }
}

export default makeTestSuite('example/test/result', {
  context: Context,
  /**
   * @param {Context} t
   */
  async getResults({ fixture }) {
    const res = await fn(fixture, this.input)
    return res
  },
})
## runs the test
hello world

/* expected */
hello world: this is a test
/**/

## fails the test
hello world

/* expected */
not hello world: this is a test
/**/
example/test/mask/default.js
  ✓  runs the test
not hello world: this is a test
  ✗  fails the test
  | Error: 'hello world: this is a test' == 'not hello world: this is a test'
  |     at fails the test (example/test/result/default.md:8:1)

example/test/mask/default.js > fails the test
  Error: 'hello world: this is a test' == 'not hello world: this is a test'
      at fails the test (example/test/result/default.md:8:1)

🦅  Executed 2 tests: 1 error.

Types

The following types are used to define the configuration of the mask.

MaskContext: The this context of mask methods which contains the mask's properties extracted from the result file.

Name Type Description
input* * The input to the mask, normally as string, but parsed into an object if jsonProps contains the 'input' value.
preamble string The text at the top of the mask result file if present.
inputs string The synchronous inputs for the fork, each on a new line in form of question: answer. This is not hard-coded, it's just a convention for naming the inputs to forks field.

MaskConfig: Configuration for making test suites.

Name Type Description Default
context (function(new: Context) | !Array<function(new: Context)> | *) The single or multiple context constructors or objects to initialise for each test. -
persistentContext (function(new: Context) | !Array<function(new: Context)> | *) The context constructor(s) that will be initialised and destroyed once per test suite, having a persistent state across tests. -
fork (string | !ForkConfig) The path to the module to fork with the mask's input split by whitespace as arguments, output of which will be compared against the code, stdout and stderr properties of the mask. Arguments with whitespace should be wrapped in speech marks, i.e. ' or ". Additionally, ForkConfig with module, getArgs, options and getOptions properties can be passed for more control of how the fork will be started. -
jsonProps !Array<string> The properties of the mask to parse as JSON values. -
jsProps !Array<string> The properties of the mask to parse into JavaScript objects. For example, a property can be written as { config: true } and will be evaluated into an object. -
splitRe !RegExp A regular expression used to detect the beginning of a new test in a mask result file. The default is /^\/\/ /gm for results from all files, and /^## /gm for results from .md files. Default /^\/\/ /gm or /^## /gm. -
propStartRe !RegExp The regex to detect the start of the property, e.g., in /⁎ propName ⁎/ it is the default regex that detects /⁎. There's no option to define the end of the regex after the name. [If copying, replace with *]. \/\‎⁎
propEndRe !RegExp The regex which indicates the end of the property, e.g, in /⁎ propName ⁎/ some prop value /⁎⁎/ it is the default that detects /⁎⁎/. [If copying, replace with *]. /\/\⁎\⁎\//
getResults (this: MaskContext, ...args: Context[]) => (* | !Promise) A possibly async function which returns results of a test. If it outputs a string, it will be compared against the expected property of the mask using string comparison. If it outputs an object, its deep equality with expected can be tested by adding 'expected' to the jsonProps. Otherwise, the result must be mapped for comparison with expected using the mapActual method. -
getTransform (this: MaskContext, ...args: Context[]) => !(Node.JS Docsstream.Transform | Promise<Node.JS Docs!stream.Transform>) A possibly async function which returns a Transform stream to be ended with the input specified in the mask's result. Its output will be accumulated and compared against the expected output of the mask. -
getReadable (this: MaskContext, ...args: Context[]) => !(Node.JS Docsstream.Readable | Promise<Node.JS Docs!stream.Readable>) A possibly async function which returns a Readable stream constructed with the input from the mask. Its output will be stored in memory and compared against the expected output of the mask. -
getThrowsConfig (this: MaskContext, ...args: Context[]) => _assertThrows.Config A function which should return a configuration for assert-throws, including fn and args, when testing an error. -
mapActual (result: *) => string The function to get a value to test against expected mask property from results returned by getResults. -
assertResults (actual: *, expected: !Object<string, *>) => (!Promise | undefined) A possibly async function containing any addition assertions on the results. The results from getResults and a map of expected values extracted from the mask's result (where jsonProps are parsed into JS objects) will be passed as arguments. -

Testing Forks

With masks, it is very easy to test fork processes.

ForkConfig: Parameters for forking.

Name Type Description Default
module* string The path to the module to fork. -
options Node.JS Docs!child_process.ForkOptions Options for the forked processed, such as ENV and cwd. -
inputs !Array<!Array<(!RegExp | string)>> Inputs to push to stdin when stdout writes data. The inputs are kept on stack, and taken off the stack when the RegExp matches the written data, e.g., [[/question/, 'answer'], [/question2/, 'answer2']]. -
stderrInputs !Array<!Array<(!RegExp | string)>> Inputs to push to stdin when stderr writes data (similar to inputs), e.g., [[/question/, 'answer'], [/question2/, 'answer2']]. -
log (boolean | { stderr: !(Node.JS Docsstream.Writable | NodeJS.WriteStream), stdout: !(Node.JS Docsstream.Writable | NodeJS.WriteStream) }) Whether to pipe data from stdout, stderr to the process's streams. If an object is passed, the output will be piped to streams specified as its stdout and stderr properties. false
includeAnswers boolean Whether to add the answers to the stderr and stdout output. true
stripAnsi boolean Remove ANSI escape sequences from the stdout and stderr prior to checking of the result. true
normaliseOutputs boolean On Windows, updates all \n to \r\n, as console.log only prints \n. false
preprocess (Preprocessor | ForkPreprocessor) The function to run on stdout and stderr before comparing it to the output. Pass an object with stdout and stderr properties for individual pre-processors. -
getArgs (this: Object, forkArgs: !Array<string>, ...contexts: Context[]) => !(Array<string> | Promise<!Array<string>>) The function to extend arguments to pass the fork based on the parsed mask input and contexts. The this context is set to the passed properties. -
getOptions (this: Object, ...contexts: Context[]) => Node.JS Docs!child_process.ForkOptions The function to get options for the fork, such as ENV and cwd, based on contexts. The this context is set to the passed properties. -

function(string): string Preprocessor: The function which processes fork's outputs before returning them for asserts.

ForkPreprocessor: An object with stdout and stderr preprocessors.

Name Type Description
stdout (stdout: string) => string How to process stdout before asserts.
stderr (stdout: string) => string How to process stderr before asserts, for example, you can strip \r symbols with clearr package.

Enabling JSDoc

The JSDoc for contexts can be enabled by specifying types for the params to the functions.

Zoroaster Mask JSDoc Contexts

Copyright & License

GNU Affero General Public License v3.0

Art Deco © Art Deco™ for ContextTesting 2020 ContextTesting AGPL-3.0

Package Sidebar

Install

npm i @zoroaster/mask

Weekly Downloads

66

Version

2.7.2

License

AGPL-3.0

Unpacked Size

179 kB

Total Files

14

Last publish

Collaborators

  • zvr