首页 > 解决方案 > 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)
    })
}

任何有关如何解决此问题的建议将不胜感激。

标签: node.jsexpressmongoosemocha.jschai

解决方案


推荐阅读