Created
March 13, 2015 22:09
-
-
Save dylants/a0aa6f58bb0926c451e0 to your computer and use it in GitHub Desktop.
When testing code which uses Mongoose models, you often run into problems when the schemas are not defined. This code provides an idea on how to mock these models (in a `beforeEach`) and clear them later (in an `afterEach`)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
var mongoose = require("mongoose"); | |
var mockMongooseModel = {}; | |
module.exports = mockMongooseModel; | |
/** | |
* This function is useful for tests that require Mongoose models | |
* loaded prior to loading the test file. This should be called in | |
* the tests `beforeEach` prior to loading the file to test. The | |
* `clearMongooseModels` function should be called in the `afterEach`. | |
*/ | |
mockMongooseModel.loadMongooseModels = function() { | |
try { | |
mongoose.model("User"); | |
} catch (err) { | |
mongoose.model("User", {}); | |
} | |
try { | |
mongoose.model("SomeOtherModel"); | |
} catch (err) { | |
mongoose.model("SomeOtherModel", {}); | |
} | |
// ... | |
}; | |
/** | |
* This mirrors the above `loadMongooseModels` to clean up what | |
* was done, and should be called in the `afterEach` of tests. | |
*/ | |
mockMongooseModel.clearMongooseModels = function() { | |
mongoose.models = {}; | |
mongoose.modelSchemas = {}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment