项目作者: ehmicky

项目描述 :
🤖 Repeat tests. Repeat tests. Repeat tests.
高级语言: JavaScript
项目地址: git://github.com/ehmicky/test-each.git
创建时间: 2019-05-22T18:41:45Z
项目社区:https://github.com/ehmicky/test-each

开源协议:Apache License 2.0

下载




test-each logo

Node
Browsers
TypeScript
Codecov
Minified size
@ehmicky">Mastodon
@ehmicky">Medium

🤖 Repeat tests. Repeat tests. Repeat tests.

Repeats tests using different inputs
(Data-Driven Testing):

Example

  1. // The examples use Ava but any test runner works (Jest, Mocha, Jasmine, etc.)
  2. import test from 'ava'
  3. import multiply from './multiply.js'
  4. import { each } from 'test-each'
  5. // The code we are testing
  6. // Repeat test using different inputs and expected outputs
  7. each(
  8. [
  9. { first: 2, second: 2, output: 4 },
  10. { first: 3, second: 3, output: 9 },
  11. ],
  12. ({ title }, { first, second, output }) => {
  13. // Test titles will be:
  14. // should multiply | {"first": 2, "second": 2, "output": 4}
  15. // should multiply | {"first": 3, "second": 3, "output": 9}
  16. test(`should multiply | ${title}`, (t) => {
  17. t.is(multiply(first, second), output)
  18. })
  19. },
  20. )
  21. // Snapshot testing. The `output` is automatically set on the first run,
  22. // then re-used in the next runs.
  23. each(
  24. [
  25. { first: 2, second: 2 },
  26. { first: 3, second: 3 },
  27. ],
  28. ({ title }, { first, second }) => {
  29. test(`should multiply outputs | ${title}`, (t) => {
  30. t.snapshot(multiply(first, second))
  31. })
  32. },
  33. )
  34. // Cartesian product.
  35. // Run this test 4 times using every possible combination of inputs
  36. each([0.5, 10], [2.5, 5], ({ title }, first, second) => {
  37. test(`should mix integers and floats | ${title}`, (t) => {
  38. t.is(typeof multiply(first, second), 'number')
  39. })
  40. })
  41. // Fuzz testing. Run this test 1000 times using different numbers.
  42. each(1000, Math.random, ({ title }, index, randomNumber) => {
  43. test(`should correctly multiply floats | ${title}`, (t) => {
  44. t.is(multiply(randomNumber, 1), randomNumber)
  45. })
  46. })

Install

  1. npm install -D test-each

This package works in both Node.js >=18.18.0 and
browsers.

This is an ES module. It must be loaded using
an import or import() statement,
not require(). If TypeScript is used, it must be configured to
output ES modules,
not CommonJS.

Usage

  1. import { each } from 'test-each'
  2. const inputs = [
  3. ['red', 'blue'],
  4. [0, 5, 50],
  5. ]
  6. each(...inputs, (info, color, number) => {})

Fires callback once for each possible combination of inputs.

Each input can be an array, a
function or an integer.

A common use case for callback is to define tests (using any test runner).

info is an object whose properties can be used to generate
test titles.

Test titles

Each combination of parameters is stringified as a title available in the
callback‘s first argument.

Titles should be included in test titles to make them descriptive and unique.

Long titles are truncated. An incrementing counter is appended to duplicates.

Any JavaScript type is
stringified,
not just JSON.

You can customize titles either by:

  1. import { each } from 'test-each'
  2. each([{ color: 'red' }, { color: 'blue' }], ({ title }, param) => {
  3. // Test titles will be:
  4. // should test color | {"color": "red"}
  5. // should test color | {"color": "blue"}
  6. test(`should test color | ${title}`, () => {})
  7. })
  8. // Plain objects can override this using a `title` property
  9. each(
  10. [
  11. { color: 'red', title: 'Red' },
  12. { color: 'blue', title: 'Blue' },
  13. ],
  14. ({ title }, param) => {
  15. // Test titles will be:
  16. // should test color | Red
  17. // should test color | Blue
  18. test(`should test color | ${title}`, () => {})
  19. },
  20. )
  21. // The `info` argument can be used for dynamic titles
  22. each([{ color: 'red' }, { color: 'blue' }], (info, param) => {
  23. // Test titles will be:
  24. // should test color | 0 red
  25. // should test color | 1 blue
  26. test(`should test color | ${info.index} ${param.color}`, () => {})
  27. })

Cartesian product

If several inputs are specified, their
cartesian product is used.

  1. import { each } from 'test-each'
  2. // Run callback five times: a -> b -> c -> d -> e
  3. each(['a', 'b', 'c', 'd', 'e'], (info, param) => {})
  4. // Run callback six times: a c -> a d -> a e -> b c -> b d -> b e
  5. each(['a', 'b'], ['c', 'd', 'e'], (info, param, otherParam) => {})
  6. // Nested arrays are not iterated.
  7. // Run callback only twice: ['a', 'b'] -> ['c', 'd', 'e']
  8. each(
  9. [
  10. ['a', 'b'],
  11. ['c', 'd', 'e'],
  12. ],
  13. (info, param) => {},
  14. )

Input functions

If a function is used instead of an array, each iteration fires it and uses
its return value instead. The function is called with the
same arguments
as the callback.

The generated values are included in test titles.

  1. import { each } from 'test-each'
  2. // Run callback with a different random number each time
  3. each(['red', 'green', 'blue'], Math.random, (info, color, randomNumber) => {})
  4. // Input functions are called with the same arguments as the callback
  5. each(
  6. ['02', '15', '30'],
  7. ['January', 'February', 'March'],
  8. ['1980', '1981'],
  9. (info, day, month, year) => `${day}/${month}/${year}`,
  10. (info, day, month, year, date) => {},
  11. )

Fuzz testing

Integers can be used instead of arrays to multiply the number of iterations.

This enables fuzz testing when combined
with input functions and libraries like
faker.js,
chance.js or
json-schema-faker.

  1. import faker from 'faker'
  2. // Run callback 1000 times with a random UUID and color each time
  3. each(
  4. 1000,
  5. faker.random.uuid,
  6. faker.random.arrayElement(['green', 'red', 'blue']),
  7. (info, randomUuid, randomColor) => {},
  8. )
  9. // `info.index` can be used as a seed for reproducible randomness.
  10. // The following series of 1000 UUIDs will remain the same across executions.
  11. each(
  12. 1000,
  13. ({ index }) => faker.seed(index) && faker.random.uuid(),
  14. (info, randomUuid) => {},
  15. )

Snapshot testing

This library works well with
snapshot testing.

Any library can be used
(snap-shot-it,
Ava snapshots,
Jest snapshots,
Node TAP snapshots, etc.).

  1. import { each } from 'test-each'
  2. // The `output` is automatically set on the first run,
  3. // then re-used in the next runs.
  4. each(
  5. [
  6. { first: 2, second: 2 },
  7. { first: 3, second: 3 },
  8. ],
  9. ({ title }, { first, second }) => {
  10. test(`should multiply outputs | ${title}`, (t) => {
  11. t.snapshot(multiply(first, second))
  12. })
  13. },
  14. )

Side effects

If callback‘s parameters are directly modified, they should be
copied to prevent side effects for the next iterations.

  1. import { each } from 'test-each'
  2. each(
  3. ['green', 'red', 'blue'],
  4. [{ active: true }, { active: false }],
  5. (info, color, param) => {
  6. // This should not be done, as the objects are re-used in several iterations
  7. param.active = false
  8. // But this is safe since it's a copy
  9. const newParam = { ...param }
  10. newParam.active = false
  11. },
  12. )

Iterables

iterable() can be used to iterate over each combination
instead of providing a callback.

  1. import { iterable } from 'test-each'
  2. const combinations = iterable(
  3. ['green', 'red', 'blue'],
  4. [{ active: true }, { active: false }],
  5. )
  6. for (const [{ title }, color, param] of combinations) {
  7. test(`should test color | ${title}`, () => {})
  8. }

The return value is an
Iterable.
This can be converted to an array with the spread operator.

  1. const array = [...combinations]
  2. array.forEach(([{ title }, color, param]) => {
  3. test(`should test color | ${title}`, () => {})
  4. })

API

each(…inputs, callback)

inputs: Array | function | integer (one or several)\
callback: (info, ...params) => void

Fires callback with each combination of params.

iterable(…inputs)

inputs: Array | function | integer (one or several)\
Return value:
Iterable<[info, ...params]>

Returns an
Iterable
looping through each combination of params.

info

Type: object

info.title

Type: string

Like params but stringified. Should be used in
test titles.

info.titles

Type: string[]

Like info.title but for each param.

info.index

Type: integer

Incremented on each iteration. Starts at 0.

info.indexes

Type: integer[]

Index of each params inside each initial
input.

params

Type: any (one or several)

Combination of inputs for the current iteration.

Support

For any question, don’t hesitate to submit an issue on GitHub.

Everyone is welcome regardless of personal background. We enforce a
Code of conduct in order to promote a positive and
inclusive environment.

Contributing

This project was made with ❤️. The simplest way to give back is by starring and
sharing it online.

If the documentation is unclear or has a typo, please click on the page’s Edit
button (pencil icon) and suggest a correction.

If you would like to help us fix a bug or add a new feature, please check our
guidelines. Pull requests are welcome!