今天在使用chai对express进行单元测试时,报错 TypeError: app.address is not a function
app.js文件内容
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const port = 3000
const routes = require('./routes/index')
// 定义数据解析器
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
// 匹配路径和路由
app.use('/', routes);
app.listen(port);
测试文件app.spec.js内容
let chai = require('chai');
let chaiHttp = require('chai-http');
let app = require('../app');
let should = chai.should();
chai.use(chaiHttp);
describe('App', () => {
it('should respond status 200', (done) => {
chai.request(app)
.get('/')
.end((err, res) => {
res.should.have.status(200);
done();
});
});
后面查找资料发现解决方法是:在app.js的app.listen(port)前加上 module.exports =
原作者解答原文是:It’s important to export the http.Server object returned by app.listen(3000) instead of just the function app, otherwise you will get TypeError: app.address is not a function.