Модульное тестирование HTTP-запроса Post с доступом к базе данных - PullRequest
0 голосов
/ 22 апреля 2020

Привет. В настоящее время я пытаюсь выучить и реализовать некоторые юнит-тесты для моих HTTP-запросов. В настоящее время у меня есть настройка базы данных SQlite и простой пост-запрос. Это тест, который я написал до сих пор:

"use strict";
process.env.NODE_ENV = 'test';

const chai = require('chai');
const chaiHttp = require('chai-http');
chai.use(chaiHttp);
const expect = chai.expect;

const app = require('../../../app');

chai.request('http://localhost:8080')
    .put('/tempValue')
    .send({sensorid: '1', sensorValue: '25.00', timeRecorded: '2020-04-12 12:30'})
    .then(function (res) {
        expect(res).to.have.status(200);
    })
    .catch(function (err) {
        throw err;
    });


Кажется, я получаю сообщение об ошибке, что не удается открыть файл базы данных. В настоящее время я просто подключаюсь к базе данных в файле приложения. js, используя const dbPath = "./database/database.db"; и const dbConnection = sqlite.open(dbPath, { Promise });

Я также, похоже, получаю ошибки о неправильном использовании .catch? Это журнал ошибок:

(node:13952) UnhandledPromiseRejectionWarning: Error: SQLITE_CANTOPEN: unable to open database file
(node:13952) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unha
ndled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:13952) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:13952) UnhandledPromiseRejectionWarning: AssertionError: expected { Object (_events, _eventsCount, ...) } to have status code 200 but got 404
    at D:\Uni Work\3rd Year\302CEM - Agile Development\Penguin Project\test\api\temperature\get.js:15:29
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:13952) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unha
ndled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)

Спасибо за любую помощь!

РЕДАКТИРОВАТЬ:

Это конкретный почтовый запрос, который я тестирую, он использует MQTT для проверки если отправляемое сообщение относится к этой структуре topi c, то вставляется в базу данных.

app.ws.use(route.all('/tempValue', function (ctx){
    client.on('message', async function(topic,message){
        console.log(topic, message.toString());
        if (topic === '302CEM/Penguin/Room1/Temperature'){
            const SQL = "INSERT INTO sensorData (sensorid, sensorValue, timeRecorded) VALUES (?,?,?)";
            try {
                const temptostring = message.toString();
                const db = await dbConnection;
                await db.run(SQL, ["1",temptostring, moment().format('YYYY-MM-DD HH:mm')]);
                ctx.websocket.send(temptostring);
            } catch (err) {
                console.log(err);
            }
        }
    })
}));
...