Error: connect ECONNREFUSED 127.0.0.1:3100

Error: connect ECONNREFUSED 127.0.0.1:3100

我是 node.I 的新手,当我 运行 npm test.

这是我的测试文件。

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;

在尝试测试 GET /hello 路由时,您的服务器不是 运行,这就是连接失败的原因。

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

在你的 test.ts 文件中,你应该导入你的服务器并确保它 listen before tests and 测试后关闭

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');
    });
});