Uni-тестирование для методов класса TypeScript с использованием postgresql в качестве службы - PullRequest
0 голосов
/ 15 сентября 2018

Я использую TypeScript в Nodejs / express с ElephantSQL (postgresql как сервис) и создал простое приложение Todo с Restfull Api, у меня есть контроллеры для маршрутов для приложения Todo, в моей базе данных только одна таблица с полями

  1. todoTitle, (Varchar)
  2. todoDescription, (Varchar)
  3. complete (Boolean Value)

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

Вот мой код

public addNewTodo(req: Request, res: Response) {
    const results = [];
    const { todoTitle, todoDescription } = req.body;
    const data = {
      todoTitle,
      todoDescription,
      complete: false
    };
    var client = new Client(connectionString);
    client.connect(err => {
      if (err) {
        console.log(err);
        return res.status(500).json({ success: false, data: err });
      }
      client
        .query(
          "INSERT INTO todoList(todoTitle, todoDescription, complete) values($1, $2, $3)",
          [data.todoTitle, data.todoDescription, data.complete]
        )
        .then(result1 => {
          client
            .query("SELECT * FROM todoList ORDER BY id asc")
            .then(result2 => {
              result2.rows.forEach(row => {
                // console.log(row);
                results.push(row);

                client
                  .end()
                  .then(() => {
                    return res.json(results);
                  })
                  .catch(err => {
                    console.log("Err: ", err);
                  });
              });
            })
            .catch(err => {
              console.log(err);
              return res.json({ success: false, data: err });
            });
        })
        .catch(err => {
          console.log(err);
          return res.json({ success: false, data: err });
        });
    });
  }

Соединение для postgresql

public postUrl: string =
    "URL";
    
 var client = new Client(this.postUrl);
    // creating the client object or instance and pass the database Url
    client.connect(function(err) {
      // call the method to verify the connection of postgresql
      if (err) {
        // if error occurs then return the error on console
        return console.error("could not connect to postgres", err);
      }
      // connection established
      client.query(
        "SELECT NOW()",
        function(err, result) {
          // if error occurs on query then return error on console
          if (err) {
            return console.error("error running query", err);
          }

          // if query succeded then return the current time on console
          // console.log("Connected to PostGreSQL at ", result.rows[0].theTime);
          console.log("Postgresql server started");
          // >> output: 2018-08-23T14:02:57.117Z

          // closing the connection when it is not in used
          client.end();
        }
      );
    });
  }
    
    
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...