错误:连接ECONNREFUSED 127.0.0.1:3100

时间:2018-09-25 16:42:50

标签: node.js typescript unit-testing mocha

我是node的新手,我得到的错误是错误:运行npm test时,连接ECONNREFUSED 127.0.0.1:3100

这是我的测试文件。

Test.ts

import * as chai from 'chai';
let chaiHttp = require('chai-http');
import * as assert from 'assertthat';
import * as request from "superagent";
chai.use(chaiHttp);
const expect = chai.expect;
describe('Checking whether the response return status 200', function() {
it('Status OK', function(done) {
return chai.request('https://localhost:3100') 
.get('/hello')
.end(function(err, res){
    if(err){
        done(err);
    }
    else{
        expect(res.body.message).to.equal('hello world');
        done();
    }
});
});
});

这是我的应用文件

app.ts

import * as express from 'express';
import {Request,Response} from 'express';
const app: express.Express = express();

app.get('/hello',(req:Request,res:Response)=>{
    res.json({
        message:"hello world"
    });
});
app.listen(3100,() =>{
    console.log("server listening");
});
export default app;

1 个答案:

答案 0 :(得分:0)

您的服务器在尝试测试 GET / hello 路由时未运行,因此无法连接。

请参见example,了解如何测试API的服务器路由。

在您的 test.ts 文件中,您应该导入服务器,并确保它在测试之前监听,并在测试之后关闭

import server from 'app.ts';
import * as chai from 'chai';
import * as assert from 'assertthat';
import * as request from 'superagent';

const chaiHttp = require('chai-http');
const expect = chai.expect;

chai.use(chaiHttp);

describe('Checking whether the response return status 200', function() {
    it('Status OK', async function(done) {
        const { res, err } = await chai.request(server).get('/hello');
        expect(res.body.message).to.equal('hello world');
    });
});
相关问题