未捕获的错误节点Js

时间:2017-05-03 14:32:10

标签: javascript node.js

所以我正在为我的简单应用程序创建一个测试套件......

我遇到了一些错误:

Server is running on port 3000
  POST /todos
    1) Uncaught error outside test suite
(node:5030) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
    2) "before each" hook for "should create a new todo"


  0 passing (2s)
  2 failing

  1)  Uncaught error outside test suite:
     Uncaught MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
      at Pool.<anonymous> (node_modules/mongoose/node_modules/mongodb-core/lib/topologies/server.js:328:35)
      at Connection.<anonymous> (node_modules/mongoose/node_modules/mongodb-core/lib/connection/pool.js:274:12)
      at Socket.<anonymous> (node_modules/mongoose/node_modules/mongodb-core/lib/connection/connection.js:177:49)
      at emitErrorNT (net.js:1278:8)
      at _combinedTickCallback (internal/process/next_tick.js:74:11)
      at process._tickCallback (internal/process/next_tick.js:98:9)

  2)  "before each" hook for "should create a new todo":
     Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.


npm ERR! Test failed.  See above for more details.

这是我的测试:

const expect = require('expect');
const request = require('supertest');
const {ObjectID} = require('mongodb');

const {app} = require('./../server');
const {Todo} = require('./../models/todo');

const todos = [{
  _id: new ObjectID(),
  text: 'First test todo'
}, {
  _id: new ObjectID(),
  text: 'Second test todo'
}];

beforeEach((done) => {
  Todo.remove({}).then(() => {
    return Todo.insertMany(todos);
  }).then(() => done());
});

describe('POST /todos', () => {
  it('should create a new todo', (done) => {
    var text = 'Test todo text';

    request(app)
      .post('/todos')
      .send({text})
      .expect(200)
      .expect((res) => {
        expect(res.body.text).toBe(text);
      })
      .end((err, res) => {
        if (err) {
          return done(err);
        }

        Todo.find({text}).then((todos) => {
          expect(todos.length).toBe(1);
          expect(todos[0].text).toBe(text);
          done();
        }).catch((e) => done(e));
      });
  });

  it('should not create todo with invalid body data', (done) => {
    request(app)
      .post('/todos')
      .send({})
      .expect(400)
      .end((err, res) => {
        if (err) {
          return done(err);
        }

        Todo.find().then((todos) => {
          expect(todos.length).toBe(2);
          done();
        }).catch((e) => done(e));
      });
  });
});

describe('GET /todos', () => {
  it('should get all todos', (done) => {
    request(app)
      .get('/todos')
      .expect(200)
      .expect((res) => {
        expect(res.body.todos.length).toBe(2);
      })
      .end(done);
  });
});

describe('GET /todos/:id', () => {
  it('should return todo doc', (done) => {
    request(app)
      .get(`/todos/${todos[0]._id.toHexString()}`)
      .expect(200)
      .expect((res) => {
        expect(res.body.todo.text).toBe(todos[0].text);
      })
      .end(done);
  });

  it('should return 404 if todo not found', (done) => {
    var hexId = new ObjectID().toHexString();

    request(app)
      .get(`/todos/${hexId}`)
      .expect(404)
      .end(done);
  });

  it('should return 404 for non-object ids', (done) => {
    request(app)
      .get('/todos/123abc')
      .expect(404)
      .end(done);
  });
});

这是我的server.js

var express = require('express');
var bodyParser = require('body-parser');
var {ObjectID} = require('mongodb');

var {mongoose} = require('./db/mongoose.js');
var {Todo} = require('./models/todo');
var {User} = require('./models/user');

var app = express();
const port = process.env.PORT || 3000;

app.use(bodyParser.json());

app.post('/todos', (req, res) =>{
  // console.log(req.body);
  var todo = new Todo({
    text: req.body.text
  });

  todo.save().then((doc) => {
    res.send(doc);
  }, (err) => {
    res.status(400).send(err);
  });
});

// GET /todos/12345
app.get('/todos/:id', (req, res) => {
  // req.send(req.params); - test localhost:3000/todos/123 on postman GET
  var id = req.params.id;

  // Validate id using isValid
 if(!ObjectID.isValid(id)){
     // Respond 404 and send back and an empty bodyParser
   return res.status(404).send();
 }


  // findById
Todo.findById(id).then((todo) =>{
if(!todo){
  return res.status(404).send();
}
res.send({todo});

}).catch((e) =>{
  res.status(400).send();
});


});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

module.exports = {app};

知道是什么导致了我的错误

大部分时间它要求它无法获得所有待办事项。

请帮忙!

2 个答案:

答案 0 :(得分:0)

  

知道是什么导致了我的错误

在某个地方,你有一个最终拒绝的承诺,你永远不会将拒绝处理程序挂钩(例如catch或第二个参数then)。究竟在哪里是调试的问题,但是例如这个代码:

beforeEach((done) => {
  Todo.remove({}).then(() => {
    return Todo.insertMany(todos);
  }).then(() => done());
});

...承诺你永远不会挂钩拒绝处理程序。因此,如果该承诺拒绝,您将得到未处理的拒绝错误。

实际问题可能不是那个特定问题(虽然它确实需要一个拒绝处理程序),但如果没有,它将是另一个使用相同的方式。

规则是:代码必须处理承诺拒绝,或传递承诺,以便可以在调用者级别处理它们。如果代码未传递承诺(例如上面的beforeEach),则必须处理拒绝。

答案 1 :(得分:0)

尝试添加此内容:

if(!module.parent){
 app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
 });
}