Mocha和Chai GET请求测试不起作用

时间:2017-12-23 12:09:35

标签: node.js express mocha httprequest chai

我试图在主根上测试GET请求' /'。该路由不存在于我的文件root.js中,因为 我希望测试失败,但它总是成功。 我不明白为什么。有3个文件:./ test / test.js,。/ server / server.js和./server/routes/index.js



/*File: ./test/test.js */
/* eslint-env mocha */
const chai = require('chai')
const chaiHttp = require('chai-http')

const { expect } = chai
const app = require('../server/server.js')

chai.use(chaiHttp)

describe('GET Home', () => {
  it('Should return Not found', () => {
    chai
      .request(app)
      .get('/', (err, res) => {
        const result = res.statusCode
        expect(result).to.equal(200)
      })
  })
})

/*File: ./server/server.js */
const express = require('express')
const bodyParser = require('body-parser')
const config = require('./config.js')
const mainRoutes = require('./routes')

const app = express()

app.set('view engine', 'jade')

app.use(bodyParser.urlencoded({ extended: false }))
app.use(mainRoutes)

app.listen(config.port, () => {
  console.log(`The application is running on localhost:${config.port}`)
})

module.exports = app

/*File: ./server/routes/index.js*/
const express = require('express')

const router = express.Router()

// router.get('/', (req, res) => {
//   res.render('home')
// })

module.exports = router




1 个答案:

答案 0 :(得分:1)

这是因为get运行异步,您需要调用done()来断言expect(result).to.equal(200)以进行检查,否则无论您的路由器是否存在,您的测试都将始终通过。如果您想了解更多信息,请查看此page并搜索Caveat

describe('GET Home', () => {
    it('Should return Not found', (done) => {
        chai
            .request(app)
            .get('/')
            .end(function (err, res) {
                const result = res.statusCode
                expect(result).to.equal(200)
                done()
            })
    })
})