Skip to content

Commit

Permalink
add tearsOfJoy to support preparing called in any order
Browse files Browse the repository at this point in the history
fixes #4
  • Loading branch information
stevemao committed Aug 13, 2016
1 parent 15e67f4 commit 8d8c44c
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 4 deletions.
28 changes: 24 additions & 4 deletions index.js
Expand Up @@ -2,22 +2,42 @@
/* eslint no-var: 0, prefer-arrow-callback: */
var once = require('once');

function toOnce(fns) {
return fns.map(function (fn) {
fn.called = false;
return once(fn);
});
}

module.exports = function BetterThanBefore() {
if (!(this instanceof BetterThanBefore)) {
return new BetterThanBefore();
}

var setups;
var teardown;
var fns;
var N = 0;

this.setups = function (fns) {
setups = fns.map(function (fn) {
return once(fn);
});
this.setups = function (_fns_) {
fns = _fns_;
setups = toOnce(fns);
};

this.preparing = function (n) {
if (N > n) {
setups = toOnce(fns);
teardown();
}

for (var i = 0; i < setups.length && i < n; i++) {
setups[i]();
}

N = n;
};

this.tearsWithJoy = function (fn) {
teardown = fn;
};
};
36 changes: 36 additions & 0 deletions readme.md
Expand Up @@ -97,6 +97,42 @@ test('B', () => {
...
```

### Not in order?

All you need to do is to provide a teardown function to `tearsWithJoy`. The teardown function needs to clean up all the setups and once `preparing()` is called, it will rebuild the setups that's needed.

```js
// class
import BetterThanBefore from 'better-than-before';
import { setups, preparing, tearsWithJoy } = new BetterThanBefore();

setups([
() => {
// setup for all tests
},
() => {
// setup for all tests except for tests only need the first setup
},
...
]);

tearsWithJoy(() => {
// teardown the setups!
});

test('B', () => {
preparing(2); // I need both first and second setup
});

test('A', () => {
// teardown is run
// then rerun the first setup
preparing(1); // I only need the first setup
});

...
```


## Caveat

Expand Down
27 changes: 27 additions & 0 deletions test.js
Expand Up @@ -6,6 +6,7 @@ import betterThanBefore from './index';
function run(t, setups, preparing) {
const fn1 = spy();
const fn2 = spy();

setups([
fn1,
fn2
Expand Down Expand Up @@ -46,3 +47,29 @@ test('factory', t => {
const {setups, preparing} = betterThanBefore();
run(t, setups, preparing);
});

test('not in order', t => {
const {setups, preparing, tearsWithJoy} = betterThanBefore();

const fn1 = spy();
const fn2 = spy();
const fn3 = spy();

setups([
fn1,
fn2
]);

tearsWithJoy(fn3);

preparing(2);
t.true(fn1.calledOnce);
t.true(fn2.calledOnce);
t.true(fn3.notCalled);

preparing(1);
t.true(fn1.calledTwice);
t.true(fn2.calledOnce);
t.true(fn1.calledBefore(fn2));
t.true(fn3.calledOnce);
});

0 comments on commit 8d8c44c

Please sign in to comment.