|
1 | 1 | # @ava/cooperate
|
2 | 2 |
|
3 | 3 | Experimental AVA plugin to enable cooperation between test files.
|
| 4 | + |
| 5 | +Install this as a development dependency alongside AVA itself: |
| 6 | + |
| 7 | +```console |
| 8 | +npm install --save-dev @ava/cooperate |
| 9 | +``` |
| 10 | + |
| 11 | +Then make sure you've enabled the shared workers experiment: |
| 12 | + |
| 13 | +`ava.config.js`: |
| 14 | + |
| 15 | +```js |
| 16 | +export default { |
| 17 | + nonSemVerExperiments: { |
| 18 | + sharedWorkers: true |
| 19 | + } |
| 20 | +}; |
| 21 | +``` |
| 22 | + |
| 23 | +## Usage |
| 24 | + |
| 25 | +Cooperation takes place within a shared context: |
| 26 | + |
| 27 | +```js |
| 28 | +const {SharedContext} = require('@ava/cooperate'); |
| 29 | + |
| 30 | +const context = new SharedContext('my-context'); |
| 31 | +``` |
| 32 | + |
| 33 | +Across all test files, contexts with the same ID (here: `my-context`) are shared. |
| 34 | + |
| 35 | +### Locks |
| 36 | + |
| 37 | +You can create a lock within a context: |
| 38 | + |
| 39 | +```js |
| 40 | +const lock = context.createLock('my-lock'); |
| 41 | +``` |
| 42 | + |
| 43 | +A lock needs to be acquired. This is asynchronous: |
| 44 | + |
| 45 | +```js |
| 46 | +const release = await lock.acquire(); |
| 47 | +``` |
| 48 | + |
| 49 | +Release the lock when you no longer need it: |
| 50 | + |
| 51 | +```js |
| 52 | +release(); |
| 53 | +``` |
| 54 | + |
| 55 | +Locks are released automatically once your tests are done. |
| 56 | + |
| 57 | +Use `acquireNow()` to either acquire the lock, or fail: |
| 58 | + |
| 59 | +```js |
| 60 | +const release = await lock.acquireNow(); |
| 61 | +``` |
| 62 | + |
| 63 | +If the lock cannot be acquired this will throw with a `LockAcquisitionError`: |
| 64 | + |
| 65 | +```js |
| 66 | +try { |
| 67 | + await lock.acquireNow(); |
| 68 | +} catch (error) { |
| 69 | + // error instanceof LockAcquisitionError |
| 70 | + // error.name === 'LockAcquisitionError' |
| 71 | + // error.lockId === 'my-lock' |
| 72 | +} |
| 73 | +``` |
| 74 | + |
| 75 | +### Reservations |
| 76 | + |
| 77 | +You can reserve primitive values like big integers, numbers and strings. Once reserved, no other test file can reserve these same values (if they use the correct shared context). Reserved values are released when your tests are done. |
| 78 | + |
| 79 | +```js |
| 80 | +const reserved = await context.reserve(1, 2, 3); |
| 81 | +// `reserved` will be an array containing those values that could be reserved. |
| 82 | +// It could be empty. |
| 83 | +``` |
0 commit comments