0

In my test environment I'm using mocha as my test runner. I have configured the NODE_ENV as "test" in a setup.js file which I configured to run with mocha on start up using

mocha --require setup.js

I am using sequelize as my ORM and I want it to init with the force flag set to true. Where should I execute the sync function?

import models from '../src/data/models';
models.sync({
  force: true
});

Since it is an async function, the tests may start before the syncing stage finished.

itaied
  • 6,827
  • 13
  • 51
  • 86
  • You need to use a before hook. Since sync returns a promise you should write before(function() { return models.sync({ force: true }) }) – aray12 Sep 28 '16 at 21:35
  • Where should I write this hook? I don't have a main file that holds all the tests, I execute the tests like this: `mocha \"src/**/*.test.js\" --require test/setup.js --compilers js:babel-register` – itaied Oct 01 '16 at 07:57
  • I commented below about how you should be explicitly rebuilding your DB for every test that depends on the DB. If you are still interested in some global hook I recommend you check our another answer I posted http://stackoverflow.com/questions/28191243/how-can-i-make-mocha-load-a-helper-js-file-that-defines-global-hooks-or-utilitie/36266849#36266849 -- basically you can write a global hook by placing it outside of any describe blocks. Again I don't really recommend it since it isn't explicit and hard to track mutations but up to you... – aray12 Oct 01 '16 at 19:54

1 Answers1

1

Add any initialization or code that you need run prior to your tests running to the global before handler.

before(function () {
  //models code here
  return models.sync({});
})
ckross01
  • 1,681
  • 2
  • 17
  • 26
  • Where do I write this `before`? I have many before handlers in my test files, but I don't have a primary file that include all the tests. – itaied Sep 28 '16 at 21:39
  • I would add a helpers file that you can `require` on any test that needs this to be setup. – ckross01 Sep 28 '16 at 21:41
  • But `sync` is an expensive process, I would like it to happen only once before all the tests. – itaied Oct 01 '16 at 07:55
  • Ideally you should be tearing down and rebuilding a DB before every single test. The reason is then you have a perfect picture of the state of the DB prior prior to each test. Otherwise you would have to track mutations throughout the test suite to track down potential bugs. It will take longer to run you tests but it will take much less time to write and debug tests -- which is completely worth it – aray12 Oct 01 '16 at 19:48