P粉6100288412023-09-03 00:41:51
Works great for me.
For example:
user.model.js
:
const mongoose = require("mongoose"); const UserSchema = mongoose.Schema({ name: { type: String, required: "Name is required", }, }); module.exports = mongoose.model("User", UserSchema);
user.controller.js
:
const User = require("./user.model"); const getUser = async (req, res) => { try { const user = await User.findOne({ name: req.body.name }); return res.status(200).json(user); } catch (err) { console.error(`Error finding user ${req.body.name}:`, err); return res.status(500).json({ message: err }); } } module.exports = { getUser }
server.js
:
const express = require('express'); const userController = require('./user.controller'); const app = express(); app.use(express.json()) app.post('/api/getUser', userController.getUser) module.exports = app;
user.test.js
:
const chai = require("chai"); const chaiHttp = require("chai-http"); const User = require("./user.model"); const server = require('./server'); chai.use(chaiHttp); chai.should(); describe("should handle mongoose errors", function () { describe("faulty User.findOne method", function () { const _User_findOne_Backup = User.findOne; beforeEach(function () { User.findOne = function () { return Promise.reject("forced error"); }; }); afterEach(function () { User.findOne = _User_findOne_Backup; }); it("signup should respond with a server error", function () { return chai .request(server) .post("/api/getUser") .send({ name: "Alice" }) .catch((err) => { const res = err.response; res.should.have.status(500); }) ; }); }); });
Test Results:
should handle mongoose errors faulty User.findOne method Error finding user Alice: forced error ✓ signup should respond with a server error 1 passing (21ms) --------------------|----------|----------|----------|----------|-------------------| File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s | --------------------|----------|----------|----------|----------|-------------------| All files | 89.19 | 100 | 88.89 | 88.57 | | server.js | 100 | 100 | 100 | 100 | | user.controller.js | 80 | 100 | 100 | 75 | 6,7 | user.model.js | 100 | 100 | 100 | 100 | | user.test.js | 88.89 | 100 | 85.71 | 88.89 | 26,27 | --------------------|----------|----------|----------|----------|-------------------|
Package version:
"chai": "^4.2.0", "chai-http": "^4.3.0", "mongodb": "^3.6.3", "mongoose": "^5.11.9", "express": "^4.17.1"