node.js - Mongoose Model.save() 在 mocha/chai /GET :id 测试中返回未定义
问题描述
我正在用 mocha/chai 测试我的路线文件夹,但是在 /get id 测试时我遇到了困难。
我正在创建一个新类别(测试)并希望在使用 ChaiHttp 请求端点之前保存它。但是,我的错误一直返回为“无法读取未定义的属性'_id'”,如下所示
Routes
/GET categories
✓ should GET all the categories (84ms)
/GET/:id categories
{
_id: 600972de84fe2307c0f2f351,
name: 'test',
icon: 'test-icon',
color: '#fffff'
}
undefined
1) it should GET a category given the id
1 passing (10s)
1 failing
1) Routes
/GET/:id categories
it should GET a category given the id:
Uncaught TypeError: Cannot read property '_id' of undefined
下面是我对 /get Route :Id 的测试
describe("/GET/:id categories", () => {
it("it should GET a category given the id", (done) => {
let category = new Category({
name: 'test',
icon: 'test-icon',
color: '#fffff',
})
console.log(category)
category.save((err, c) => {
console.log(c)
const id = c._id
chai
.request(`${process.env.BASE_URL}${process.env.API_URL}`)
.get("/categories/" + id)
.send(c)
.end((err, res) => {
expect(res.body).to.be.an("object")
expect(res).to.have.property("statusCode", 200)
expect(res.body).to.have.property("_id").eql(id)
done()
})
})
})
})
category.save() 之前的 console.log 显示了下面的代码,返回的代码与 Postman 请求中的代码完全相同。
{
_id: 600972de84fe2307c0f2f351,
name: 'test',
icon: 'test-icon',
color: '#fffff'
}
但是, Model.save() 承诺似乎没有将其保存或传递到 chai 请求中。
我在我的 App.js 中运行一个测试数据库,如下所示。
// Database
if (process.env.NODE_ENV === 'test') {
const mongoUriTest = process.env.TEST_DATABASE
mongoose
.connect(mongoUriTest, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
})
.then((res) => {
console.log('Successfully connected to Test_Database')
})
.catch((err) => {
console.log(err)
})
} else {
const mongoUri = process.env.DATABASE
mongoose
.connect(mongoUri, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
})
.then((res) => {
console.log('Successfully connected to Database')
})
.catch((err) => {
console.log(err)
})
}
任何有关如何解决此问题的建议将不胜感激。
解决方案
推荐阅读
- python - PySpark - 有没有办法迭代多列并用列的最大数(+1)填充 NA?
- spss-modeler - SPSS建模器学生激活不起作用
- python - 如何隐藏 SLURM 的 sbatch 的作业提交消息
- javascript - RadAsyncUpload OnClientValidationFailed 无故触发
- typescript - 如何使用枚举值作为打字稿接口中的键?
- javascript - 如何在 onclick 函数中加上单引号?
- html - 为什么外这里没有完全包围内部?
- mysql - 如何在 MySQL 的 ExtractValue 中使用 XPath `(//path)[n]` 语法
- spring - 如何使用 mockito 在 Spring Boot 中测试资源加载器
- python - 计算熊猫数据帧非连续行的滚动平均值