UNPKG

1.87 kBJavaScriptView Raw
1const Mocha = require('mocha')
2const log = require('debug')('rocha')
3// verbose output during e2e tests
4const e2e = require('debug')('rocha:e2e')
5const la = require('lazy-ass')
6const is = require('check-more-types')
7const chalk = require('chalk')
8
9const order = require('./src/order-of-tests')
10const cache = require('./src/order-cache')
11la(is.object(cache), 'missing test order object')
12
13function rocha (options) {
14 options = options || {}
15
16 const mocha = options.mocha || new Mocha()
17
18 log('starting rocha with options')
19 log(JSON.stringify(options, null, 2))
20
21 var specFilenames = options.spec
22 if (!specFilenames) {
23 console.error('Missing spec file pattern')
24 process.exit(-1)
25 }
26
27 if (typeof specFilenames === 'string') {
28 specFilenames = [specFilenames]
29 }
30
31 specFilenames.forEach(mocha.addFile.bind(mocha))
32
33 mocha.suite.beforeAll(function () {
34 const cachedOrder = cache.load()
35 if (cachedOrder) {
36 log('reordering specs like last time')
37 order.set(mocha.suite, cachedOrder)
38 } else {
39 const randomOrder = order.shuffle(mocha.suite)
40 const names = order.collect(randomOrder)
41 e2e('shuffled names:')
42 e2e('%j', names)
43 }
44
45 // the order might be out of date if any tests
46 // were added or deleted, thus
47 // always collect the order
48 const testNames = order.collect(mocha.suite)
49 cache.save(testNames)
50 })
51
52 mocha.run(function (failures) {
53 process.on('exit', function () {
54 if (failures === 0) {
55 cache.clear()
56 } else {
57 const filename = cache.filename()
58 la(is.unemptyString(filename), 'missing save filename')
59 console.error('Failed tests order saved in', chalk.yellow(filename))
60 console.error('If you run Rocha again, the same failed test order will be used')
61 }
62 process.exit(failures)
63 })
64 })
65}
66
67module.exports = rocha