joeglin2000
joeglin2000

Reputation: 85

Get beforeEach to only run for tests in the file it is in

I have two mocha test files, each with their own beforeEach function. The beforeEach from each file runs for all testcases. Better explained with code:

user.test.js:

beforeEach((done) => {
  console.log('user before each');
  done();
});
describe('Running user tests', () => {

  it('user test #1',  () => {
    console.log('in user test 1');
  });

  it('user test #2',  () => {
    console.log('in user test 2');
  });

});

todo.test.js

beforeEach((done) => {
  console.log('todo before each');
  done();
});

describe('Running todo tests', () => {

  it('todo test #1',  (done) => {
    console.log('in todo test 1');
    done();
  });

  it('todo test #2',  (done) => {
    console.log('in todo test 2');
    done();
  });

});

package.json

{
  "name": "before-each",
  "version": "1.0.0",
  "description": "",
  "main": "todo.test.js",
  "scripts": {
    "test": "mocha **/*.test.js"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "mocha": "^5.2.0"
  }
}

output when running: npm test

  Running todo tests
todo before each
user before each
in todo test 1
    ✓ todo test #1
todo before each
user before each
in todo test 2
    ✓ todo test #2

  Running user tests
todo before each
user before each
in user test 1
    ✓ user test #1
todo before each
user before each
in user test 2
    ✓ user test #2


  4 passing (7ms)

Is there any way to get the beforeEach() in the todo file to only run for the tests in the todo file, and beforeEach() in the user file to only run for user tests? I come from Java/JUnit background and this behaves quite differently.

Thanks!

Upvotes: 0

Views: 663

Answers (1)

JLRishe
JLRishe

Reputation: 101700

Move the beforeEach inside the describe. That's the correct place to put a beforeEach that belongs to a particular describe:

describe('Running user tests', () => {
  beforeEach((done) => {
    console.log('user before each');
    done();
  });

  it('user test #1',  () => {
    console.log('in user test 1');
  });

  it('user test #2',  () => {
    console.log('in user test 2');
  });
});

Upvotes: 3

Related Questions