Как мне сделать простой тест маршрута с этой настройкой? - PullRequest
0 голосов
/ 04 января 2019

РЕДАКТИРОВАТЬ: После долгих усилий по поиску решения я убежден, что это связано с тем, как файл package.json компилирует большую часть сайта на лету.Webpack, и лепет участвуют.Я думаю, что решением будет настройка тестового сервера, который работает с полностью скомпилированным сайтом.

Я прорабатываю курс узла и хочу остановиться, прежде чем идти дальше, и добавить к нему тестирование.

Банкомат Я просто хотел бы иметь возможность проверитьдомашний маршрут откатывает назад 200. С почтальоном это не проблема, но я не могу заставить мокко его проверить.

app.js:

const express = require("express");
const session = require("express-session");
const mongoose = require("mongoose");
const MongoStore = require("connect-mongo")(session);
const path = require("path");
const cookieParser = require("cookie-parser");
const bodyParser = require("body-parser");
const passport = require("passport");
const { promisify } = require("es6-promisify");
const flash = require("connect-flash");
const expressValidator = require("express-validator");
const routes = require("./routes/index");
const helpers = require("./helpers");
const errorHandlers = require("./handlers/errorHandlers");

// create our Express app
const app = express();

// view engine setup
app.set("views", path.join(__dirname, "views")); // this is the folder where we keep our pug files
app.set("view engine", "pug"); // we use the engine pug, mustache or EJS work great too

// serves up static files from the public folder. Anything in public/ will just be served up as the file it is
app.use(express.static(path.join(__dirname, "public")));

// Takes the raw requests and turns them into usable properties on req.body
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Exposes a bunch of methods for validating data. Used heavily on userController.validateRegister
app.use(expressValidator());

// populates req.cookies with any cookies that came along with the request
app.use(cookieParser());

// Sessions allow us to store data on visitors from request to request
// This keeps users logged in and allows us to send flash messages
app.use(
  session({
    secret: process.env.SECRET,
    key: process.env.KEY,
    resave: false,
    saveUninitialized: false,
    store: new MongoStore({ mongooseConnection: mongoose.connection })
  })
);

// // Passport JS is what we use to handle our logins
app.use(passport.initialize());
app.use(passport.session());

// // The flash middleware let's us use req.flash('error', 'Shit!'), which will then pass that message to the next page the user requests
app.use(flash());

// pass variables to our templates + all requests
app.use((req, res, next) => {
  res.locals.h = helpers;
  res.locals.flashes = req.flash();
  res.locals.user = req.user || null;
  res.locals.currentPath = req.path;
  next();
});

// promisify some callback based APIs
app.use((req, res, next) => {
  req.login = promisify(req.login, req);
  next();
});

// After allllll that above middleware, we finally handle our own routes!
app.use("/", routes);

// If that above routes didnt work, we 404 them and forward to error handler
app.use(errorHandlers.notFound);

// One of our error handlers will see if these errors are just validation errors
app.use(errorHandlers.flashValidationErrors);

// Otherwise this was a really bad error we didn't expect! Shoot eh
if (app.get("env") === "development") {
  /* Development Error Handler - Prints stack trace */
  app.use(errorHandlers.developmentErrors);
}

// production error handler
app.use(errorHandlers.productionErrors);

// done! we export it so we can start the site in start.js
module.exports = app;

Приложение настроено для запуска маршрутов через файл в маршрутах / называется index.js.Затем этот файл вызывает файл представления ...

Хотя мой тест не может быть правильно маршрутизирован.

const expect = require("expect");
const request = require("supertest");
const app = require("./../../app");

describe("Dummy Test", () => {
  it("Should return 5", () => {
    const result = 2 + 3;
    expect(5);
  });
});

describe("Get /home", () => {
  it("should get home", done => {
    request(app)
      .get("/home")
      .expect(200)
      .end(done);
  });
});

Он всегда возвращает 500. Я могу сделать репо публичным, если поможет более глубокий взгляд.

1 Ответ

0 голосов
/ 04 января 2019

Не уверен, что я решу это, но надеюсь, что это, по крайней мере, вызовет у вас новые идеи отладки.Я обычно использую superagent с Jest для тестирования, но это выглядит как более-менее похожая настройка.

Я сделал некоторое сравнение кода с документами (https://www.npmjs.com/package/supertest).

В этом примере есть некоторая обработка ошибок в .end (). Интересно, если добавление может помочь вам диагностировать?

describe('POST /users', function() {
  it('responds with json', function(done) {
    request(app)
      .post('/users')
      .send({name: 'john'})
      .set('Accept', 'application/json')
      .expect(200)
      .end(function(err, res) {
        if (err) return done(err);
        done();
      });
  });
});

Кроме того, в этом примере показано, как done добавляется в виде запятой вместо .end(done) в отдельной строке. Ваш текущий способ также отображается, но это еще один способ попробовать.

describe('GET /user', function() {
  it('respond with json', function(done) {
    request(app)
      .get('/user')
      .set('Accept', 'application/json')
      .expect('Content-Type', /json/)
      .expect(200, done);
  });
});

Если ничего из этого не помогло, мои последние мысли о том, что на самом деле возвращает ваш «/ home» маршрут? Я вижу импорт маршрутов в файле вашего приложения, но не вижу этих реальных маршрутов для справки.пробовали дополнительные обработчики console.log / error в вашем / home маршруте, чтобы проверить перспективу серверной части того, что отправляется?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...