aboutsummaryrefslogtreecommitdiff
path: root/node_modules/ava/lib/sequence.js
blob: 1e5960a98cb471b42f2c840ba30f4e56e344fb11 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
'use strict';

const beforeExitSubscribers = new Set();
const beforeExitHandler = () => {
	for (const subscriber of beforeExitSubscribers) {
		subscriber();
	}
};
const onBeforeExit = subscriber => {
	if (beforeExitSubscribers.size === 0) {
		// Only listen for the event once, no matter how many Sequences are run
		// concurrently.
		process.on('beforeExit', beforeExitHandler);
	}

	beforeExitSubscribers.add(subscriber);
	return {
		dispose() {
			beforeExitSubscribers.delete(subscriber);
			if (beforeExitSubscribers.size === 0) {
				process.removeListener('beforeExit', beforeExitHandler);
			}
		}
	};
};

class Sequence {
	constructor(runnables, bail) {
		if (!Array.isArray(runnables)) {
			throw new TypeError('Expected an array of runnables');
		}

		this.runnables = runnables;
		this.bail = bail || false;
	}

	run() {
		const iterator = this.runnables[Symbol.iterator]();

		let activeRunnable;
		const beforeExit = onBeforeExit(() => {
			if (activeRunnable.finishDueToInactivity) {
				activeRunnable.finishDueToInactivity();
			}
		});

		let allPassed = true;
		const finish = () => {
			beforeExit.dispose();
			return allPassed;
		};

		const runNext = () => {
			let promise;

			for (let next = iterator.next(); !next.done; next = iterator.next()) {
				activeRunnable = next.value;
				const passedOrPromise = activeRunnable.run();
				if (!passedOrPromise) {
					allPassed = false;

					if (this.bail) {
						// Stop if the test failed and bail mode is on.
						break;
					}
				} else if (passedOrPromise !== true) {
					promise = passedOrPromise;
					break;
				}
			}

			if (!promise) {
				return finish();
			}

			return promise.then(passed => {
				if (!passed) {
					allPassed = false;

					if (this.bail) {
						// Stop if the test failed and bail mode is on.
						return finish();
					}
				}

				return runNext();
			});
		};

		return runNext();
	}
}

module.exports = Sequence;