如何在通过摩卡咖啡测试Express应用程序时如何启动服务器



我想使用摩卡咖啡为我在Visual Studio中编写的Nodejs/Express应用程序编写单元测试。我到处都可以寻找一个简单的教程,但找不到我想要的东西。我在使用断言测试5 = 5等进行测试时看到了许多教程。但这不是我想做的。

我正在尝试通过VS添加JavaScript Mocha单元测试文件,然后我真正想要的就是打开应用程序的主页,检查身体中的某些内容并通过测试。如果我想从测试Explorer窗口运行测试,则Nodejs应用程序无法运行,如果它不运行,则不会收到主页的请求。

所以我不确定测试本身是否应该以某种方式启动该应用程序?我觉得我在22次接球中,缺少基本知识,只是看不到它在任何地方描述。

您要寻找的最常称为 api test - 集成测试的一部分而不是单位测试。如果测试触摸网络,数据库或I/O,则最常见的是 Integration Test 而不是。

现在要问您的问题。为了测试您的应用程序。

  • module.export您的app服务器。
  • 在您的测试中,使用Chai-HTTP进行测试路线。
  • require在测试中您的app,并在测试路由时使用它而不是URL。

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

服务器代码

// 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

测试代码

// 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: 'john@doe.com'
      })
      .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)
      })
  })
})

然后,只需从根目录中运行测试:

$ mocha test/registration.spec.js

最新更新