MockModel.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. const SandboxedModule = require('sandboxed-module')
  2. const mongoose = require('mongoose')
  3. /**
  4. * Imports a model as we would usually do with e.g. `require('models/User')`
  5. * an returns a model an schema, but without connecting to Mongo. This allows
  6. * us to use model classes in tests, and to use them with `sinon-mongoose`
  7. *
  8. * @param modelName the name of the model - e.g. 'User'
  9. * @param requires additional `requires` to be passed to SanboxedModule in
  10. * the event that these also need to be stubbed. For example,
  11. * additional dependent models to be included
  12. *
  13. * @return model and schema pair - e.g. { User, UserSchema }
  14. */
  15. module.exports = (modelName, requires = {}) => {
  16. const model = {}
  17. requires['../infrastructure/Mongoose'] = {
  18. createConnection: () => {
  19. return {
  20. model: () => {},
  21. }
  22. },
  23. model: (modelName, schema) => {
  24. model[modelName + 'Schema'] = schema
  25. model[modelName] = mongoose.model(modelName, schema)
  26. },
  27. Schema: mongoose.Schema,
  28. Types: mongoose.Types,
  29. }
  30. SandboxedModule.require('../../../../app/src/models/' + modelName, {
  31. requires,
  32. })
  33. return model
  34. }