2015-12-04 4 views
0

У меня есть набор тестов, в следующем формате:мокко MongoDB (Mongoose) испытания висит при запуске с Грантом

var mongoTest = require('../mongoTest.js'); 

//Connect to test DB before tests and disconnect after 
before(function(done) { 
    mongoTest.mongoConnect(done); 
}); 

after(function(done) { 
    mongoose.disconnect(done); 
}) 

//Load Data Files 
var testData = require('../testData.js') 
var deviceAndLocationAnswers = testData.deviceAndLocationAnswers 

//Repeated Functions: 
var clearCollections = function(coll, callback) { 
    mongoose.connection.db.dropCollection(coll.collectionName, 
     function(err, result) { 
      callback(); 
     }); 
} 

describe('Testing functions that use the Breakers collections', function(){ 
    //Test Setup 
    var req = {query: {device: testData.powerConsumptionDevice}} 

    before(function(done) { 
     this.timeout(15000); 
     async.forEach(mongoose.connection.collections, clearCollections, 
      function(err) { 
       if (err) {console.log(err)}; 
       done(); 
      }) 
    }); 

    before(function(done) { 
     this.timeout(15000); 
     Breakers.create(testData.breakersData, function(err, model){ 
      done(err); 
     }); 
    }); 

    after(function(done) { 
     this.timeout(15000); 
     async.forEach(mongoose.connection.collections, clearCollections, 
      function(err) { 
       if (err) {console.log(err)}; 
       done(); 
      }) 
    }); 

    // Tests 
    describe('Testing powerConsumption Function', function() { 
     it('Should produce some output', function(done) { 
      this.timeout(15000); 
      dbFunctions.powerConsumption(req, function(result) { 
       result.should.exist; 
       done(); 
      }); 
     }); 
     it('Should produce the same results as the mock up from testData', function(done) { 
      this.timeout(15000); 
      dbFunctions.powerConsumption(req, function(result) { 
       result.should.be.deep.equal(testData.powerConsumptionResults); 
       done(); 
      }); 
     }); 
    }); 
}); 

mongoTest исходит из следующего файла:

var mongoose = require('mongoose') 
var dBaseURL = 'mongodb://xxxx:[email protected]#####.mongolab.com:zzzz/myDB'; // details removed 
exports.mongoConnect = function(callback) { 
    mongoose.connect(dBaseURL, function(err) { 
     if(err) { 
     console.log('MongoDB Connection Error', err); 
     } else { 
      console.log('MongoDB Connection Successful') 
     } 
     callback(); 
    }); 
}; 

У меня также есть еще один файл, в котором я использовал mockgoose для извлечения базы данных, и третий файл тестов, который просто проверяет простые функции.

Эти тесты успешно выполняются, когда я запускаю их отдельно. Но когда я пытаюсь запустить всех трех с хрюканьем, все происходит на первом перед вызовом в одном из тестов, которые касаются Монго. В базу данных Mongo не входит соединение. Я даже не могу получить информацию, разместив console.log() в обратном вызове connect.

Вот файл ворчание:

module.exports = function(grunt) { 
    grunt.loadNpmTasks('grunt-mocha-test'); 
    grunt.initConfig({ 
     pkg: grunt.file.readJSON('package.json'), 
     // Configure a mochaTest task 
     mochaTest: { 
      jenkins: { 
       options: { 
       reporter: 'spec', 
       captureFile: 'tests/results.txt', // Optionally capture the reporter output to a file 
       quiet: false, // Optionally suppress output to standard out (defaults to false) 
       clearRequireCache: true 
       }, 
      src: ['tests/unit/*.js'] 
      } 
     } 
    }); 
    grunt.registerTask('default', 'mochaTest'); 
}; 

Я сделал новую установку с НПМ. Специфическим механизмом неудачных тестов является первый тайм-аут before через 30 секунд.

Кто-нибудь знает, как это исправить? Я чувствую, что пропустил какой-то ключевой шаг, но я был Googling для решения в течение часа без везения. Я попытался установить четкий требуемый кеш в true и false, но ни одна из них, похоже, ничего не делает.

ответ

0

Я не уверен, какое конкретное взаимодействие вызывало мои тесты, но они преуспевают, если я отделяю насмешливые и не посмеянные тесты к их собственным объектам.

Вот код, который работает:

module.exports = function(grunt) { 
    grunt.loadNpmTasks('grunt-mocha-test'); 
    grunt.initConfig({ 
     pkg: grunt.file.readJSON('package.json'), 
     mochaTest: { 
      unitTests: { 
       options: { 
       reporter: 'spec', 
       captureFile: 'tests/unitTestResults.txt', // Optionally capture the reporter output to a file 
       quiet: false, // Optionally suppress output to standard out (defaults to false) 
       clearRequireCache: true 
       }, 
      src: ['tests/unit/helpersTest.js', 'tests/unit/dbFunctionTests.js'] 
      }, mockedUnitTests: { 
       options: { 
       reporter: 'spec', 
       captureFile: 'tests/mockedUnitTestResults.txt', // Optionally capture the reporter output to a file 
       quiet: false, // Optionally suppress output to standard out (defaults to false) 
       clearRequireCache: true 
       }, 
      src: ['tests/unit/dbFunctionMockTests.js'] 
      } 
     } 
    }); 
    grunt.registerTask('default', 'mochaTest'); 
}; 
Смежные вопросы