套接字在超级测试mongodb节点REST API中挂断

时间:2019-02-17 16:09:54

标签: node.js mongodb

我正在为任务分配一个REST API,目前我没有几个端点,并且我正在忙于编写测试用例。当我进行测试以检查数据库是否正确连接时,会发生奇怪的事情。我有几种GETPOST方法。如果我传递有效数据,POST始终会通过。因此,我继续进行测试以检查数据库连接。

当我将POST方法放在GET之前时,测试“ API与mongodb连接”通过。

describe('Admin adds a new user', function () {
    it('Request to add a user without authorization', function (done) {
        request(app)
            .post('/api/admin/user/add')
            .send({
                username: "Padmal1",
                password: "abc123",
                isAdmin: false
            })
            .expect(400, done);
    });
});

describe('API connects with mongodb', function () {
    it('Successful database connection', function (done) {
        request(app)
            .get('/api')
            .expect(200, done);
    });
});

all tests passing when post before get

但是当我将GET放在POST之前时,测试“ API与mongodb连接”失败,提示socket hang up

describe('API connects with mongodb', function () {
    it('Successful database connection', function (done) {
        request(app)
            .get('/api')
            .expect(200, done);
    });
});

describe('Admin adds a new user', function () {
    it('Request to add a user without authorization', function (done) {
        request(app)
            .post('/api/admin/user/add')
            .send({
                username: "Padmal1",
                password: "abc123",
                isAdmin: false
            })
            .expect(400, done);
    });
});

test fail when get before post

以下是此API中使用的方法;

const cors = require('cors');
const express = require('express');
const bodyParser = require('body-parser');
const MongoClient = require('mongodb').MongoClient
const ObjectID = require('mongodb').ObjectID;

const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());

var db = undefined;

MongoClient.connect('mongodb://localhost:27017/posdb',
    { useNewUrlParser: true })
    .then(client => {
        db = client.db('posdb');
        db.collection('col_users').createIndex({ "username": 1 }, { unique: true });
    })
    .catch(res => {
        console.log(res.name);
    });

app.get('/api', (req, res) => {
    // Test endpoint to test database connection
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({
        "status": "API is up and running with a Mongo DB @ " +
            db.serverConfig.s.host + ':' + db.serverConfig.s.port
    }));
});

app.post('/api/admin/user/add', (req, res) => {
    try {
        if (req.headers.authorization) {
            // TODO: Verify authentication
            try {
                if (req.body.username) {
                    db.collection('col_users').insertOne(req.body, function (err, r) {
                        if (err) {
                            res.writeHead(403, { 'Content-Type': 'application/json' });
                            res.end(JSON.stringify({ error: "Duplicate username ..." }));
                        } else {
                            res.writeHead(200, { 'Content-Type': 'application/json' });
                            res.end(JSON.stringify({ _id: r.insertedId }));
                        }
                    });
                } else {
                    res.writeHead(404, { 'Content-Type': 'application/json' });
                    res.end(JSON.stringify({ error: "No user to add ..." }));
                }
            } catch (e) {
                if (e instanceof SyntaxError) {
                    res.writeHead(503, { 'Content-Type': 'application/json' });
                    res.end(JSON.stringify({ error: "JSON format seems wrong ..." }));
                }
            }
        } else {
            throw new ReferenceError;
        }
    } catch (e) {
        if (e instanceof TypeError) {
            res.writeHead(500, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify({ error: "Database seems out of our hands ..." }));
        } else if (e instanceof ReferenceError) {
            res.writeHead(400, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify({ error: "Invalid user request ..." }));
        }
    }
});

我在此问题上做了一些research,但对此一无所知。我对NodeJS开发非常陌生。当我在浏览器中尝试链接时,似乎可以正常工作,给出预期的结果。

web browser

我还尝试向标头添加connection:keep-alive,但是没有用。只有这样才能在GET测试之后进行POST测试。可能是什么问题?谢谢你的提示:)

0 个答案:

没有答案