Node.js – 使用摩卡testing快速应用时出现“错误:连接ECONNREFUSED”
首先,我不听80或8080端口,我正在听1337端口。
我使用express创build了一个简单的HTTP服务器。 这里是启动服务器的app.js脚本。
require('./lib/server').listen(1337)
服务器脚本位于lib/server.js
文件中,因为在testing脚本中也会使用相同的脚本。
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)
最后是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() }) }) })
但是我得到一个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)
我真的不明白为什么这个,因为我的testing脚本似乎是逻辑的。 我运行服务器node app.js
并手动testinglocalhost:1337/john
和localhost:1337/sam
,它工作的很好!
任何帮助? 谢谢。
要使http.get()
正常工作,需要将资源的完整path指定为第一个参数:
http.get('http://localhost:1337/john', function(res){ assert(200, res.statusCode) done() })
http.get({path: '/john', port: 1337}, function(res){ //... });
应该pipe用。 如果没有指定其他内容,http.get将假定端口80。