«Не удается установить заголовки после их отправки» - это ошибка, которую я получаю при запуске теста npm - PullRequest
0 голосов
/ 01 октября 2018

Я получаю следующую ошибку на консоли: Это полное сообщение, которое я получаю;

server running on port 5000
  API Orders Endpoint Testing
    1) should list ALL orders on / GET
    2) should get a SINGLE order on /:id GET
Error: Can't set headers after they are sent.
    at validateHeader (_http_outgoing.js:491:11)
    at ServerResponse.setHeader (_http_outgoing.js:498:3)
    at ServerResponse.header (C:\Users\Alhaja-Adams-R-K\documents\web-projects\f                                ast-food-fast\node_modules\express\lib\response.js:767:10)
    at ServerResponse.send (C:\Users\Alhaja-Adams-R-K\documents\web-projects\fas                                t-food-fast\node_modules\express\lib\response.js:170:12)
    at ServerResponse.json (C:\Users\Alhaja-Adams-R-K\documents\web-projects\fas                                t-food-fast\node_modules\express\lib\response.js:267:15)
    at ServerResponse.send (C:\Users\Alhaja-Adams-R-K\documents\web-projects\fas                                t-food-fast\node_modules\express\lib\response.js:158:21)
    at getOrderById (C:/Users/Alhaja-Adams-R-K/documents/web-projects/fast-food-                                
    fast/controllers/orders.js:31:26)
    at Layer.handle [as handle_request] (C:\Users\Alhaja-Adams-R-K\documents\web                                -projects\fast-food-fast\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-food-fast\nod                                e_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-foo                                d-fast\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\Alhaja-Adams-R-K\documents\web                                -projects\fast-food-fast\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-food-fast\node_modu                                les\express\lib\router\index.js:281:22
    at param (C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-food-fast\no                                de_modules\express\lib\router\index.js:354:14)
    at param (C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-food-fast\no                                de_modules\express\lib\router\index.js:365:14)
    at Function.process_params (C:\Users\Alhaja-Adams-R-K\documents\web-projects                                \fast-food-fast\node_modules\express\lib\router\index.js:410:3)
    at next (C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-food-fast\nod                                e_modules\express\lib\router\index.js:275:10)
    at Function.handle (C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-fo                                od-fast\node_modules\express\lib\router\index.js:174:3)
    at router (C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-food-fast\n                                ode_modules\express\lib\router\index.js:47:12)
    at Layer.handle [as handle_request] (C:\Users\Alhaja-Adams-R-K\documents\web                                -projects\fast-food-fast\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-food-f                                ast\node_modules\express\lib\router\index.js:317:13)
    at C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-food-fast\node_modu                                les\express\lib\router\index.js:284:7
    at Function.process_params (C:\Users\Alhaja-Adams-R-K\documents\web-projects                                \fast-food-fast\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-food-fast\nod                                e_modules\express\lib\router\index.js:275:10)
    at jsonParser (C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-food-fa                                st\node_modules\express\node_modules\body-parser\lib\types\json.js:109:7)
    at Layer.handle [as handle_request] (C:\Users\Alhaja-Adams-R-K\documents\web                                -projects\fast-food-fast\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-food-f                                ast\node_modules\express\lib\router\index.js:317:13)
    at C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-food-fast\node_modu                                les\express\lib\router\index.js:284:7
    at Function.process_params (C:\Users\Alhaja-Adams-R-K\documents\web-projects                                \fast-food-fast\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-food-fast\nod                                e_modules\express\lib\router\index.js:275:10)
    at urlencodedParser (C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-f                                ood-fast\node_modules\body-parser\lib\types\urlencoded.js:91:7)
    at Layer.handle [as handle_request] (C:\Users\Alhaja-Adams-R-K\documents\web                                -projects\fast-food-fast\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-food-f                                ast\node_modules\express\lib\router\index.js:317:13)
    at C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-food-fast\node_modu                                les\express\lib\router\index.js:284:7
    at Function.process_params (C:\Users\Alhaja-Adams-R-K\documents\web-projects                                \fast-food-fast\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-food-fast\nod                                e_modules\express\lib\router\index.js:275:10)
    at jsonParser (C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-food-fa                                st\node_modules\body-parser\lib\types\json.js:110:7)
    at Layer.handle [as handle_request] (C:\Users\Alhaja-Adams-R-K\documents\web                                -projects\fast-food-fast\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-food-f                                ast\node_modules\express\lib\router\index.js:317:13)
    at C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-food-fast\node_modu                                les\express\lib\router\index.js:284:7
    at Function.process_params (C:\Users\Alhaja-Adams-R-K\documents\web-projects                                \fast-food-fast\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-food-fast\nod                                e_modules\express\lib\router\index.js:275:10)
    at expressInit (C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-food-f                                ast\node_modules\express\lib\middleware\init.js:40:5)
    at Layer.handle [as handle_request] (C:\Users\Alhaja-Adams-R-K\documents\web                                -projects\fast-food-fast\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-food-f                                ast\node_modules\express\lib\router\index.js:317:13)
    at C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-food-fast\node_modu                                les\express\lib\router\index.js:284:7
    at Function.process_params (C:\Users\Alhaja-Adams-R-K\documents\web-projects                                \fast-food-fast\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-food-fast\nod                                e_modules\express\lib\router\index.js:275:10)
    at query (C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-food-fast\no                                de_modules\express\lib\middleware\query.js:45:5)
    at Layer.handle [as handle_request] (C:\Users\Alhaja-Adams-R-K\documents\web                                -projects\fast-food-fast\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-food-f                                ast\node_modules\express\lib\router\index.js:317:13)
    at C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-food-fast\node_modu                                les\express\lib\router\index.js:284:7
    at Function.process_params (C:\Users\Alhaja-Adams-R-K\documents\web-projects                                \fast-food-fast\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-food-fast\nod                                e_modules\express\lib\router\index.js:275:10)
    at Function.handle (C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-fo                                od-fast\node_modules\express\lib\router\index.js:174:3)
    at Function.handle (C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-fo                                od-fast\node_modules\express\lib\application.js:174:10)
    at Server.app (C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-food-fa                                st\node_modules\express\lib\express.js:39:9)
    at emitTwo (events.js:126:13)
    at Server.emit (events.js:214:7)
    at parserOnIncoming (_http_server.js:619:12)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:115:23)
    3) should get place an order on / POST
    4) should update the status of an order on /:id GET

  0 passing (344ms)
  4 failing

  1) API Orders Endpoint Testing
       should list ALL orders on / GET:
     Uncaught AssertionError: expected { Object (success, message, ...) } to have property 'name'
      at C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-food-fast\test\test.js:26:25
      at Test.Request.callback (node_modules\superagent\lib\node\index.js:716:12)
      at parser (node_modules\superagent\lib\node\index.js:916:18)
      at IncomingMessage.res.on (node_modules\superagent\lib\node\parsers\json.js:19:7)
      at endReadableNT (_stream_readable.js:1064:12)
      at _combinedTickCallback (internal/process/next_tick.js:138:11)
      at process._tickCallback (internal/process/next_tick.js:180:9)

  2) API Orders Endpoint Testing
       should get a SINGLE order on /:id GET:
     Uncaught AssertionError: expected { Object (success, message, ...) } to have property 'name'
      at C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-food-fast\test\test.js:37:25
      at Test.Request.callback (node_modules\superagent\lib\node\index.js:716:12)
      at parser (node_modules\superagent\lib\node\index.js:916:18)
      at IncomingMessage.res.on (node_modules\superagent\lib\node\parsers\json.js:19:7)
      at endReadableNT (_stream_readable.js:1064:12)
      at _combinedTickCallback (internal/process/next_tick.js:138:11)
      at process._tickCallback (internal/process/next_tick.js:180:9)

  3) API Orders Endpoint Testing
       should get place an order on / POST:
     Uncaught AssertionError: expected { Object (success, message, ...) } to have property 'name'
      at C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-food-fast\test\test.js:53:25
      at Test.Request.callback (node_modules\superagent\lib\node\index.js:716:12)
      at parser (node_modules\superagent\lib\node\index.js:916:18)
      at IncomingMessage.res.on (node_modules\superagent\lib\node\parsers\json.js:19:7)
      at endReadableNT (_stream_readable.js:1064:12)
      at _combinedTickCallback (internal/process/next_tick.js:138:11)
      at process._tickCallback (internal/process/next_tick.js:180:9)

  4) API Orders Endpoint Testing
       should update the status of an order on /:id GET:

      Uncaught AssertionError: expected { Object (domain, _events, ...) } to have status code 200 but got 400
      + expected - actual

      -400
      +200

      at C:\Users\Alhaja-Adams-R-K\documents\web-projects\fast-food-fast\test\test.js:62:20
      at Test.Request.callback (node_modules\superagent\lib\node\index.js:716:12                                )
      at parser (node_modules\superagent\lib\node\index.js:916:18)
      at IncomingMessage.res.on (node_modules\superagent\lib\node\parsers\json.js:19:7)
      at endReadableNT (_stream_readable.js:1064:12)
      at _combinedTickCallback (internal/process/next_tick.js:138:11)
      at process._tickCallback (internal/process/next_tick.js:180:9)

Я получаю ошибку всякий раз, когда я запускаю тест npm, и мои тесты для API с mocha и chai не проходят,Я использую подход MVC.Я экспортировал свое приложение / сервер из файла app.js.Но я все еще получаю эту ошибку.Пожалуйста, что я делаю не так?

test / test.js

import chai from 'chai';
import chaiHttp from 'chai-http';
import app from '../app.js';

chai.use(chaiHttp);
let should = chai.should();

describe('API Orders Endpoint Testing', () => {
    //Test to get all orders
    it('should list ALL orders on / GET', (done) => {
        chai.request(app)
            .get('/api/v1/orders')
            .end((err, res) => {
                res.should.have.status(200);
                res.body.should.be.a('object');
                res.body.should.have.property('name');
                res.body.should.have.property('quantity');
                done();
            });
    });
    //Test to Fetch a single order
    it('should get a SINGLE order on /:id GET', (done) => {
        const id = 1;
        chai.request(app)
            .get(`/api/v1/orders/${id}`)
            .end((err, res) => {
                res.should.have.status(200);
                res.body.should.be.a('object');
                res.body.should.have.property('name');
                res.body.should.have.property('quantity');
                done();
            });
    });
    //Test to place a new order
    it('should get place an order on / POST', (done) => {
        chai.request(app)
            .post('/api/v1/orders')
            .send({
                orderStatus: "Delivered",
                name: "Fish-Roll",
                quantity: "10",
                price: "100",
                date: new Date().toDateString()
                })
            .end((err, res) => {
                res.should.have.status(200);
                res.body.should.be.a('object');
                res.body.should.have.property('name');
                res.body.should.have.property('quantity');
                done();
            });
    });
    //Test to update status of an order
    it('should update the status of an order on /:id GET', (done) => {
        const id = 2;
        chai.request(app)
            .put(`/api/v1/orders/${id}`)
            .end((err, res) => {
                res.should.have.status(200);
                res.body.should.be.a('object');
                res.body.should.have.property('name');
                res.body.should.have.property('quantity');
                done();
            });
    });

}); 

controllers / orders.js

import db from '../db/db';

//ALL ORDERS
export const allOrders = (req, res) => {
 res.status(200).send({
    success: 'true',
    message: 'orders retrieved successfully',
    orders: db
  });
}

//FETCH AN ORDER
export const getOrderById = (req, res) => {
      const id = parseInt(req.params.id, 10);
  db.map((order) => {
     if (order.id === id) {
       return res.status(200).send({
          success: 'true',
          message: 'order retrieved successfully',
          order
       });
      }
  });
  return res.status(404).send({
    success: 'false',
    message: 'order does not exist'
  });
}

//PLACE AN ORDER
export const placeAnOrder = (req, res) =>{
    if(!req.body.name) {
    return res.status(400).send({
      success: 'false',
      message: 'name is required'
    });
  } else if(!req.body.quantity) {
    return res.status(400).send({
      success: 'false',
      message: 'quantity is required'
    });
  }
 const order = {
   id: db.length + 1,
   orderStatus: req.body.status,
   name: req.body.name,
   quantity: req.body.quantity,
   price: "10",
   date: new Date().toDateString()
 }
 db.push(order);
 return res.status(200).send({
   success: 'true',
   message: 'order added successfully',
   order: order
 })
}

//UPDATE ORDER STATUS
export const updateOrderStatus = (req, res) => {
  const id = parseInt(req.params.id, 10);
  let orderFound;
  let itemIndex;
  db.map((order, index) => {
    if (order.id === id) {
      orderFound = order;
      itemIndex = index;
    }
  });

  if (!orderFound) {
    return res.status(404).send({
      success: 'false',
      message: 'order not found'
    });
  }

  if (!req.body.name) {
    return res.status(400).send({
      success: 'false',
      message: 'name is required'
    });
  } else if (!req.body.quantity) {
    return res.status(400).send({
      success: 'false',
      message: 'quantity is required'
    });
  }

  const updatedOrder = {
    id: orderFound.id,
    name: req.body.name || orderFound.name,
    quantity: req.body.quantity || orderFound.quantity
  };

  db.splice(itemIndex, 1, updatedOrder);

  return res.status(200).send({
    success: 'true',
    message: 'order added successfully',
    updatedOrder: updatedOrder
  });
}

1 Ответ

0 голосов
/ 01 октября 2018

возврат в .map не возвращается из функции getOrderById.Похоже, ваш код пытается выполнить строку res.status(404) после завершения карты и отправки статуса 200 (в случае поиска).

Попробуйте использовать цикл for здесь -

export const getOrderById = (req, res) => {
  const id = parseInt(req.params.id, 10);
  for(var i = 0; i < db.length; i++){
    var order = db[i];
    if (order.id === id) {
      return res.status(200).send({
        success: 'true',
        message: 'order retrieved successfully',
        order
     });
     break;
    }
  }
  return res.status(404).send({
    success: 'false',
    message: 'order does not exist'
  });
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...