Wednesday, 3 May 2017

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

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!



via Jim Carter

No comments:

Post a Comment