mongoose 无法使用mocha、chai和supertest运行单元测试用例,正在获取:-错误:E连接拒绝:连接被拒绝

evrscar2  于 2023-01-21  发布在  Go
关注(0)|答案(2)|浏览(119)

我无法找到这个问题的解决方案,有时在数据库连接建立之前运行了一个单元测试用例。如果有人知道这个错误,请发布解决方案。
app.js

import express from 'express';
const app = express();
app.use(cors());
const session = require('express-session');
const http = require('http').createServer(app);
const io = require('socket.io').listen(http);
import config from './config/environment';
import initializeDB from './config/seed';
import mongoose from 'mongoose';
const connecString = config.getConstants().mongo.uri;
import fileUpload from 'express-fileupload';
import registerRoutes from './routes';
import cors from 'cors';
import { run_cron_job } from './config/helper';
import passport from 'passport';
require('./config/passport');

require('dotenv').config();

mongoose.connect(connecString, {
    useNewUrlParser: false
}).then(()=>{
    console.log("Blik database connected successfully.");
    initializeDB();
})
.catch((err)=>{
    console.log(err);
});

//Middlware
app.use(passport.initialize());
app.use(fileUpload());
app.use(express.json());

registerRoutes(app);

io.on('connection', function(socket){
    // console.log('A user connected');
    socket.on('disconnect', function(){
        // console.log('A user disconnected');
    });
});

export function experiment(){
    io.sockets.emit('new_token');
}

http.listen(config.getPort(),async ()=>{
    run_cron_job();
    console.log("Server is running on port " + config.getPort());
})
export default app;

workspace.test.js

import { expect } from 'chai';
import request from 'supertest';
import app from '../../app';

describe('Workspace', async () => {

    it('should return 200 if workspace created sucessfully', async () => {
        const payload = {
            workspace_name: 'testing workspace',
            email: 'abc@gmail.com',
            mobile: '9721867247',
            name: 'abc',

        };

        const res = await request(app).post('api/v1/workspace').send(payload);
        // console.log('response', res);
        console.log('responseWorkspace =>', res);
    });

});

package.json

"scripts": {
    "start": "babel-node server/app.js",
    "prod": "babel-node server/app.js production",
    "test": "SET NODE_ENV=test&&mocha --require @babel/register --slow 100 --timeout 10000 server/**/*.test.js"
  }
    • 我收到的错误代码**
Server is running on port 3001
   Workspace
(node:20352) DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead.
Blik database connected successfully.
    1) should return 200 if workspace created sucessfully

  0 passing (2s)
  1 failing

  1) Workspace
       should return 200 if workspace created sucessfully:
     Error: ECONNREFUSED: Connection refused
      at Test.assert (node_modules\supertest\lib\test.js:165:15)
      at Server.localAssert (node_modules\supertest\lib\test.js:131:12)
      at emitCloseNT (net.js:1618:8)
      at process._tickCallback (internal/process/next_tick.js:63:19)
0pizxfdo

0pizxfdo1#

你该换衣服了
request(app).post("api/v1/workspace")

request(app).post("/api/v1/workspace")
否则,将抛出错误:
错误:已拒绝连接:连接被拒绝
例如
app.ts

import express from "express";

const app = express();
const port = 3000;
const http = require("http").createServer(app);

app.post("/api/v1/workspace", (req, res) => {
  res.sendStatus(200);
});

if (require.main === module) {
  http.listen(port, () => {
    console.log("Server is running on port " + port);
  });
}

export default app;

app.test.ts

import { expect } from "chai";
import request from "supertest";
import app from "./app";

describe("Workspace", () => {
  it("should return 200 if workspace created sucessfully", async () => {
    const payload = {
      workspace_name: "testing workspace",
      email: "abc@gmail.com",
      mobile: "9721867247",
      name: "abc",
    };

    const res = await request(app)
      .post("/api/v1/workspace")
      .send(payload);
    expect(res.status).to.be.eq(200);
  });
});

集成测试结果与覆盖率报告:

Workspace
    ✓ should return 200 if workspace created sucessfully

  1 passing (28ms)

-------------|----------|----------|----------|----------|-------------------|
File         |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-------------|----------|----------|----------|----------|-------------------|
All files    |       90 |       50 |       75 |    88.89 |                   |
 app.test.ts |      100 |      100 |      100 |      100 |                   |
 app.ts      |       80 |       50 |       50 |       80 |             12,13 |
-------------|----------|----------|----------|----------|-------------------|

源代码:https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/59065236

ix0qys7i

ix0qys7i2#

我也面临着同样的问题,然后我尝试了一件事,它为我工作。
将根文件作为服务器导入,如-

const server = require('../../../app');

相关问题