hta*_*irt 8 testing mocha.js node.js express
首先,我没有收听端口80或8080.我正在收听端口1337.
我用express创建了一个简单的HTTP服务器.这是启动服务器的app.js脚本.
require('./lib/server').listen(1337)
Run Code Online (Sandbox Code Playgroud)
服务器脚本位于lib/server.js文件中,因为测试脚本中也将使用相同的脚本.
var http = require('http')
, express = require('express')
, app = express()
app.get('/john', function(req, res){
res.send('Hello John!')
})
app.get('/sam', function(req, res){
res.send('Hello Sam!')
})
module.exports = http.createServer(app)
Run Code Online (Sandbox Code Playgroud)
并且,最后test/test.js:
var server = require('../lib/server')
, http = require('http')
, assert = require('assert')
describe('Hello world', function(){
before(function(done){
server.listen(1337).on('listening', done)
})
after(function(){
server.close()
})
it('Status code of /john should be 200', function(done){
http.get('/john', function(res){
assert(200, res.statusCode)
done()
})
})
it('Status code of /sam should be 200', function(done){
http.get('/sam', function(res){
assert(200, res.statusCode)
done()
})
})
it('/xxx should not exists', function(done){
http.get('/xxx', function(res){
assert(404, res.statusCode)
done()
})
})
})
Run Code Online (Sandbox Code Playgroud)
但是我得到了3/3错误:
Hello world
1) Status code of /john should be 200
2) Status code of /sam should be 200
3) /xxx should not exists
? 3 of 3 tests failed:
1) Hello world Status code of /john should be 200:
Error: connect ECONNREFUSED
at errnoException (net.js:770:11)
at Object.afterConnect [as oncomplete] (net.js:761:19)
2) Hello world Status code of /sam should be 200:
Error: connect ECONNREFUSED
at errnoException (net.js:770:11)
at Object.afterConnect [as oncomplete] (net.js:761:19)
3) Hello world /xxx should not exists:
Error: connect ECONNREFUSED
at errnoException (net.js:770:11)
at Object.afterConnect [as oncomplete] (net.js:761:19)
Run Code Online (Sandbox Code Playgroud)
我真的不明白为什么这样,因为我的测试脚本似乎是逻辑.我运行服务器node app.js并手动测试,localhost:1337/john而且localhost:1337/sam效果很好!
有帮助吗?谢谢.
对于http.get()工作,你需要的完整路径分配到的资源作为第一个参数:
http.get('http://localhost:1337/john', function(res){
assert(200, res.statusCode)
done()
})
Run Code Online (Sandbox Code Playgroud)
http.get({path: '/john', port: 1337}, function(res){
//...
});
Run Code Online (Sandbox Code Playgroud)
应该管用.如果没有指定其他内容,http.get将假定端口80.
| 归档时间: |
|
| 查看次数: |
18799 次 |
| 最近记录: |