I am having some serious trouble wrapping my head around how to unit test the mongoose ORM piece of my app. I am starting to think using mongoose isn't worth all the effort..
Edit: forgot to mention - I am using Jest as the test framework.
So what I have is simple entity called Detail. Below is the code setup.
detail.model.js
const mongoose = require("mongoose");
const { Schema } = mongoose;
const schema = new Schema({
refId: Number,
text: String,
dateCreated: { type: Date, default: Date.now },
createdBy: { type: mongoose.Schema.Types.ObjectId, ref: "User" }
});
module.exports = mongoose.model("Detail", schema);
detail.service.js
const db = require("../../_helpers/db");
const { Detail } = db;
async function getAll({ createdBy }) {
return Detail.find({ createdBy });
}
async function create(payload) {
return new Detail(payload).save();
}
module.exports = {
getAll,
create
};
and the helper db.js
db.js
const mongoose = require("mongoose");
const User = require("../users/user.model");
const Detail = require("../entities/detail/detail.model");
const logger = require("../logging/winstonLogger");
mongoose.connect(process.env.MONGODB_URI, {}, err => {
if (err) return logger.error("Failed to connect to DB", err);
logger.info("DB connection established!");
});
module.exports = {
User,
Detail
};
So the setup is pretty basic. And it works, to a degree. I've tested it with postman (there's some more code involved to support express routing).
What I am trying to do is unit test the entity service but it just wont work. The Detail model resolves and the constructor fails/
const mongoose = require("mongoose");
jest.mock("mongoose");
jest.spyOn(mongoose, "connect").mockImplementationOnce(() => {
console.log("Mock connect triggerred!");
});
const mockUser = {
username: "admin",
firstName: "Rick",
lastName: "Sanchez"
};
describe("Detail Service", function() {
describe("Given a valid detail", function() {
it("should create a new detail", async function(done) {
const detailService = require("../../src/entities/detail/detail.service");
const detail = {
refId: "507f1f77bcf86cd799439011",
text: "This is a test detail 1",
dateCreated: Date.now(),
createdBy: mockUser
};
const mongooseResult = await detailService.create(detail);
done();
});
});
});
Detail is not a constructor
TypeError: Detail is not a constructor
at Object.create (C:\x\x\x-server\src\entities\detail\detail.service.js:14:10)