ava: afterEach and beforeEach not running?

I’ve reproduced this bug in this repo. From the README there:

The test directory has a bug.js and a workaround.js.

If you run: npm install and then npm t you’ll get:

~/Developer/ava-beforeEach-afterEach-bug (master)
⛄  $ npm run test -s

  ✔ workaround › first log
  ✔ workaround › second log
  ✔ bug › first log
  ✖ bug › second log   
  t.true(console.log.calledOnce)
                     |          
                     false      


  1 test failed

  1. second log
  AssertionError: false === true
    Test.fn (test/bug.js:16:3)


For some reason, it appears that perhaps the cleanup function is not run between the two test runs.

It’s using the latest version of AVA. Specifically, I spotted this here. Let me know if you need more info!

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Comments: 18 (17 by maintainers)

Most upvoted comments

@kentcdodds They don’t require that tests run serially. It’s because console.log is global, so shared between the two tests. This means that console.log is referring to the same spy. So in this situation, it’s necessary to run them serially. If you are able (which is not the case here) to use the context object, you don’t have to run them serially because it’s a totally new object.

import test from 'ava';
import sinon from 'sinon';

test.beforeEach(t => {
    t.context.log = sinon.spy();
});

test.afterEach(t => {
    t.context.log.restore();
});

test('first', t => {
    t.context.log('first');
    t.true(t.context.log.calledOnce);
});

test('second', t => {
    t.context.log('second');
    t.true(t.context.log.calledOnce);
});

Shared variable

import test from 'ava';

let i = 0;

test.beforeEach(t => {
    i++;
});

test.afterEach(t => {
    i--;
});

test('first', t => {
    console.log(i);
});

test('second', t => {
    console.log(i);
});

Output:

2
2

Context variable

import test from 'ava';

test.beforeEach(t => {
    t.context.i = (t.context.i || 0) + 1;
});

test.afterEach(t => {
    t.context.i--;
});

test('first', t => {
    console.log(t.context.i);
});

test('second', t => {
    console.log(t.context.i);
});

Output:

1
1

And it doesn’t make sense to me that the tests are using the same spy because the spy should be reset before each test.

They are, but AVA is just too fast 😃.

Look at the execution flow

beforeEach
beforeEach
first
second
afterEach

Note: Not sure though why the second afterEach isn’t called. Bug? @sindresorhus

As you see, the console.log will be the same for first and second, being the one created in the second call to beforeEach. So yes, they are shared 😃.

Exactly. From the moment you have something shared (which might not seem to be shared in the first place), you will have to execute them serially.

@SamVerschueren On a side note, the above would be great as a recipe. Hint hint 😉