我想使用Mocha为我在Visual Studio中编写的Nodejs / Express应用程序编写单元测试。我到处寻找一个简单的教程,但找不到我要找的东西。我已经看过许多使用assert创建测试的教程来测试5 = 5等,但这不是我想做的。
我正在尝试通过VS添加JavaScript Mocha单元测试文件,然后我真正希望它做的就是打开我的应用程序的主页,检查正文中的一些内容并通过测试。如果我想从Test Explorer窗口运行测试,则nodejs应用程序无法运行,如果它没有运行,则无法接收主页请求。
所以我不确定测试本身是否应该以某种方式启动应用程序或什么?我觉得自己陷入困境22并且缺少基础知识,只是在任何地方都看不到它。
答案 0 :(得分:2)
您正在寻找的内容通常称为 API测试 - 集成测试的一部分,而不是单元测试。如果测试涉及网络,数据库或I / O,则最常见的是集成测试。
现在回答你的问题。为了在不事先手动启动服务器的情况下测试app.js代码,您可以执行以下操作:
module.export
您的app
服务器。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
然后只需使用以下命令从根目录运行测试:
grails:
gorm:
multiTenancy:
mode: DISCRIMINATOR
tenantResolverClass: security.CompanyTenantResolver