Response.body不会通过supertest返回任何内容,但是在服务器中可以正常工作吗?

时间:2019-12-30 21:40:38

标签: javascript node.js express mongoose supertest

我正在尝试用supertest测试我的应用程序。当我运行nodemon index.js并转到该地址进行GET请求时,我得到了包含正确数据的有效响应。 用app.js调用Supertest,它的内容也低于下面。 但是,当我这样做时,响应主体将返回[]。为什么会这样呢?我对这一切还是陌生的,因此,如果必须添加任何内容,请这么说。

index.js:

const app = require('./app') // the actual Express app
const http = require('http')
const config = require('./utils/config')

const server = http.createServer(app)

server.listen(config.PORT, () => {
  console.log('Server running')
})

app.js:

const config = require('./utils/config')
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const cors = require('cors')
const blogsRouter = require('./controllers/blogs')
const middleware = require('./utils/middleware')
const mongoose = require('mongoose')

console.log('connecting to', config.MONGODB_URI)

mongoose.connect(config.MONGODB_URI, { useNewUrlParser: true })
  .then(() => {
    console.log('connected to MongoDB')
  })
  .catch((error) => {
    console.log('error connection to MongoDB:', error.message)
  })

app.use(cors())
app.use(express.static('build'))
app.use(bodyParser.json())
app.use(middleware.requestLogger)

app.use('/api/blogs', blogsRouter)

app.use(middleware.unknownEndpoint)
app.use(middleware.errorHandler)

module.exports = app

这是我运行测试的部分: blog_api.test.js:

const mongoose = require('mongoose')
const supertest = require('supertest')
const app = require('../app')

const api = supertest(app)

test('blogs are returned as json', async () => {
  await api
    .get('/api/blogs')
    .expect(200)
    .expect('Content-Type', /application\/json/)
})

test('there are one blog', async () => {
    const response = await api.get('/api/blogs')
    //response doesn't return anything yet works fine in server?
    expect(response.body.length).toBe(1)
  })


afterAll(() => {
  mongoose.connection.close()
})

第一个测试工作正常,但第二个失败,因为response.body返回[]

出于良好的考虑,下面是我实际定义GET请求应执行的代码: 在我的控制器中:

blogsRouter.get('/', (request, response) => {
    Blog.find({}).then(notes => {
        let resJson = response.json(notes.map(note => note.toJSON()))

        return resJson
    })
})

0 个答案:

没有答案