关于node.js:通过Mocha测试Express应用程序时如何启动服务器

How to startup the server when testing an Express app via Mocha

我想使用Mocha为我在Visual Studio中编写的Node.js / Express应用程序编写单元测试。我到处都可以搜寻简单的教程,但没有找到想要的内容。我已经看过许多使用assert来测试5 = 5的测试的教程,依此类推。但这不是我想要的。

我试图通过VS添加一个JavaScript Mocha单元测试文件,然后我真正想要做的就是打开应用程序的主页,检查正文中的某些内容并通过测试。如果要从"测试资源管理器"窗口运行测试,则nodejs应用程序无法运行,如果未运行,则没有任何内容可以接收对主页的请求。

所以我不确定测试本身是否应该以某种方式启动应用程序或什么?我觉得自己陷入了困境,却错过了基本知识,只是在任何地方都看不到它。


您正在寻找的东西通常被称为API测试-集成测试的一部分,而不是单元测试。如果测试涉及网络,数据库或I / O,则最常见的是集成测试。

现在您的问题。为了测试您的app.js代码而无需事先手动启动服务器,您可以执行以下操作:

  • module.export您的app服务器。
  • 在测试中,使用chai-http测试路由。
  • 在测试中require您的app,并在测试路由时使用它代替URL。

这里的关键是第一个要点。您必须export您的app,以便您可以require并在测试中使用它。这使您可以跳过在其中启动单独的服务器进程的部分,以在其上运行测试。

服务器代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// app.js

const express = require('express')
const app = express()
const bodyParser = require('body-parser')

app.use(bodyParser.json())

// Routes

app.post('/register', (req, res) => {
  const requiredFields = ['name', 'email']

  if (requiredFields.every(field => Object.keys(req.body).includes(field))) {
    // Run business logic and insert user in DB ...
    res.sendStatus(204)
  } else {
    res.sendStatus(400)
  }
})

app.listen(3000)

// export your app so you can include it in your tests.
module.exports = app

测试码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// test/registration.spec.js
const chai = require('chai')
const chaiHttp = require('chai-http')
// `require` your exported `app`.
const app = require('../app.js')

chai.should()
chai.use(chaiHttp)

describe('User registration', () => {
  it('responds with HTTP 204 if form fields are valid', () => {
    return chai.request(app)
      .post('/register')
      .send({
        name: 'John Doe',
        email: '[email protected]'
      })
      .then(res => {
        res.should.have.status(204)
      })
      .catch(err => {
        throw err
      })
  })

  it('responds with HTTP 400 if some fields are missing', () => {
    return chai.request(app)
      .post('/register')
      .send({
        name: 'John Doe'
      })
      .catch(err => {
        err.should.have.status(400)
      })
  })
})

然后只需使用以下命令从根目录运行测试:

1
$ mocha test/registration.spec.js