UNPKG

1.87 kBJavaScriptView Raw
1
2process.env.NODE_ENV = 'test';
3
4const db = require('../../db/db');
5const migrations = require('../../db/migrations');
6const cache = require('../../cache');
7const config = require('../../config');
8const logger = require('../../logger');
9const cls = require('../../cls');
10const app = require('../../app');
11const plugins = require('../../plugins');
12
13var context;
14
15//
16var reinitDatabase = function(callback) {
17 const database = config.mysql.database;
18 config.mysql.database = null;
19 db.init();
20
21 var DROP_DATABASE = 'DROP DATABASE IF EXISTS `' + database + '`;';
22 var CREATE_DATABASE = 'CREATE DATABASE `' + database + '`;';
23
24 db.query(DROP_DATABASE, function() {
25 db.query(CREATE_DATABASE, function() {
26 config.mysql.database = database;
27 db.init(config);
28 migrations.migrate(function() {
29 logger.info('Igo dev: reinitialized test database');
30 callback();
31 });
32 });
33 });
34};
35
36// before running tests
37before(function(done) {
38 app.configure();
39 if (config.skip_reinit_db) {
40 return done();
41 }
42 reinitDatabase(done);
43});
44
45// begin transaction before each test
46beforeEach(function(done) {
47 const _this = this;
48 cls.getNamespace().run(function() {
49 _this.currentTest.fn = cls.bind(_this.currentTest.fn);
50 context = cls.getNamespace().active;
51 cache.flushall(function() {
52 db.beginTransaction(function() {
53 if (config.test && config.test.beforeEach) {
54 return config.test.beforeEach(done);
55 }
56 done();
57 });
58 })
59 });
60});
61
62// rollback transaction after each test
63afterEach(function(done) {
64 // cls hack: restore context manually
65 cls.getNamespace().active = context;
66 db.rollbackTransaction(function() {
67 if (config.test && config.test.afterEach) {
68 return config.test.afterEach(done);
69 }
70 done();
71 });
72
73});