简体   繁体   English

未捕获的错误节点Js

[英]Uncaught error Node Js

So I am creating a test suite for my simple app... 所以我正在为我的简单应用程序创建一个测试套件...

I bump into some errors: 我碰到一些错误:

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.

Here's my test: 这是我的测试:

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

And here's my server.js 这是我的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};

Any idea what's causing my error 不知道是什么导致我的错误

Most of the time its asking that it can't get all todos. 大多数时候,它要求不能获得所有待办事项。

Please help! 请帮忙!

Any idea what's causing my error 不知道是什么导致我的错误

Somewhere, you have a promise that ultimately rejects, which you never hook up a rejection handler for (eg, catch or the second argument to then ). 在某个地方,您有一个最终拒绝的承诺,您永远不会为其连接拒绝处理程序(例如, catchthen的第二个参数)。 Exactly where that is is a matter of debugging, but for instance this code: 确切地说,这是调试的问题,但是例如以下代码:

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

...has a promise you never hook up a rejection handler for. ...有一个您永远不会为之拒绝处理程序的承诺。 So if that promise rejects, you'll get the unhandled rejection error. 因此,如果该承诺被拒绝,您将收到未处理的拒绝错误。

The actual problem may not be that specific one (though it does need a rejection handler), but if not it'll be another used the same way. 实际的问题可能不是那个特定的问题(尽管它确实需要一个拒绝处理程序),但如果不是,它将是另一个以相同的方式使用的问题。

The rule is: Code must either handle promise rejections, or pass on the promise so they can be handled at the caller's level. 规则是:代码必须处理承诺拒绝,或者传递承诺,以便可以在调用者级别处理它们。 If code doesn't pass on the promise (such as beforeEach above), it has to handle rejections. 如果代码没有兑现承诺(例如上述的beforeEach ),则它必须处理拒绝。

Try adding this: 尝试添加以下内容:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在节点js中未定义Mustache错误:未捕获错误 - Mustache is not defined error in node js : Uncaught error 节点js TLS未连接错误连接失败?怎么抓? - Node js TLS uncaught error on connection fail? How to catch? Function 未定义 node.js 未捕获参考错误 - Function is not defined node.js Uncaught Reference error 使用节点运行 js 时出现此错误:Uncaught SyntaxError: Unexpected identifier - Getting this error on running js using node : Uncaught SyntaxError: Unexpected identifier 库在节点js中的茉莉花测试期间引发未捕获的错误 - Library is throwing an uncaught error during jasmine test in node js Node.js PostgreSQL http - 更新查询中未捕获的错误 - Node.js PostgreSQL http - Uncaught error on UPDATE query 在Node.js中解决“Uncaught ReferenceError:require is not defined”错误 - Resolve “Uncaught ReferenceError: require is not defined” error in Node.js Node.js 基本错误:Uncaught TypeError: Binance is not a function - Node.js basic error: Uncaught TypeError: Binance is not a function sigma.js:添加图节点时出错。 错误:未捕获节点“ 159684”已存在 - sigma.js : error on adding Graph Node. ERROR: Uncaught The node “159684” already exists 未捕获的 ReferenceError - 黄瓜节点 js - Uncaught ReferenceError - cucumber node js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM