Я пытаюсь запустить базовый c тест для функции в моем hosts.js
, но я сталкиваюсь с приведенной ниже ошибкой, которая, как мне кажется, связана с supertest
в моем hosts.test.js
файле, который копируется в конце этого сообщения.
> shodan-api@0.0.0 test /home/eth3rk1ll/Development/shodan-api
> jest
FAIL tests/unit/hosts.test.js
POST /
✕ should save the host if it is valid (4ms)
● POST / › should save the host if it is valid
TypeError: Cannot read property 'address' of undefined
11 | const exec = async () => {
12 | return await request(server)
> 13 | .post('/api/hosts')
| ^
14 | .send({ hostName: hostName, ipV4Address: ipV4Address });
15 | }
16 |
at Test.Object.<anonymous>.Test.serverAddress (node_modules/supertest/lib/test.js:55:18)
at new Test (node_modules/supertest/lib/test.js:36:12)
at Object.post (node_modules/supertest/index.js:25:14)
at exec (tests/unit/hosts.test.js:13:10)
at Object.it (tests/unit/hosts.test.js:23:15)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 1.458s, estimated 2s
Ran all test suites.
npm ERR! Test failed. See above for more details.
Я искал в Интернете решения, и наиболее относительные из них приведены ниже в файлах app.js
или index.js
.
var express = require('express');
var app = express();
app.use('/api', UserRoutes);
module.exports = app;
Это мой index.js
file:
const express = require('express');
const mongoose = require('mongoose');
const hosts = require('./routes/hosts');
const app = express();
const port = process.env.PORT || 3000;
const server = app.listen(port, () =>
console.log(`Listening on port ${port}...`)
);
mongoose.connect('mongodb://localhost/shodan-api', {
useNewUrlParser: true,
useUnifiedTopology: true
});
app.use(express.json());
app.use('/api/hosts', hosts);
module.exports = server;
module.exports = app;
Я объявляю express и экспортирую объект app
согласно решению.
Однако это не устраняет ошибку.
Ниже приведены мои hosts.test.js
и hosts.js
файлы.
Чего мне не хватает для исправления ошибки?
/routes/hosts.js
var express = require('express');
var router = express.Router();
const { Host, validate } = require('../models/host');
// Create a new host object
router.post('/', async (req, res) => {
const { error } = validate(req.body);
if(error) return validationError(res, error);
let host = new Host({
hostName: req.body.hostName,
ipV4Address: req.body.ipV4Address
});
host = await host.save();
res.send(host);
});
module.exports = router;
/tests/unit/hosts.test.js
const request = require('supertest');
const {Host} = require('../../models/host');
let server;
describe('POST /', () => {
let hostName;
let ipV4Address;
const exec = async () => {
return await request(server)
.post('/api/hosts')
.send({ hostName: hostName, ipV4Address: ipV4Address });
}
beforeEach(() => {
hostName = 'test host';
ipV4Address = '192.168.0.10';
})
it('should save the host if it is valid', async () => {
await exec();
const host = await Host.find(validHostDetails);
expect(host).not.toBeNull();
});
// it('should return the host if it is valid', async () => {
// const res = await exec();
// expect(res.body).toHaveProperty('_id');
// expect(res.body).toHaveProperty('hostName', 'test host');
// expect(res.body).toHaveProperty('ipV4Address', '192.168.0.10');
// });
});