Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Provide per test "context" that is shared with "beforeEach" #122

Closed
jamestalmage opened this issue Nov 3, 2015 · 2 comments
Closed

Comments

@jamestalmage
Copy link
Contributor

Right now beforeEach has limited utility in concurrent tests. The following won't work because both tests manipulate a shared variable and run concurrently:

var obj;

test.beforeEach(t => {
  obj = // ... some verbose setup code.  
  t.end();
});

test('test1', t => {
  // tests with side-affects  on `obj` 

  // sometime later
  t.end();
});

test('test2', t => {
  // tests with side-affects  on `obj` 

  // sometime later
  t.end();
});

To address this, I think it would be good to provide a this reference that is shared between beforeEach and the individual test:

var globalCount = 1;

test.beforeEach(t => {
  this.count = globalCount;
  globalCount++;
  t.end();
});

test('test1', t => {
  t.plan(1);
  var self = this;
  setTimeout(() => t.is(self.count, 1));
});

test('test2', t => {
  t.plan(1);
  var self = this;
  setTimeout(() => t.is(self.count, 2));
});

The above is maybe not the best example and might fail since I doubt we are guaranteeing test instantiation order in a concurrent testing framework.

Another alternative might be to pass the context as an optional second arg:

var globalCount = 1;

test.beforeEach((t, ctx) => {
  ctx.count = globalCount;
  globalCount++;
  t.end();
});

test('test1', (t, ctx) => {
  t.plan(1);
  setTimeout(() => t.is(ctx.count, 1));
});

test('test2', (t, ctx) => {
  t.plan(1);
  setTimeout(() => t.is(ctx.count, 2));
});

This has the advantage of avoiding self reference verbosity.

@schnittstabil
Copy link

Doesn't t.context do the job?

@jamestalmage
Copy link
Contributor Author

CRAP!
How did I miss that?!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants