ExpressJS api测试抛出异常无法读取未定义的属性“地址”

时间:2019-03-16 12:06:59

标签: javascript node.js api express supertest

应用程序将启动并运行正常,因此我可以调用我的api:

"dev": "env-cmd ./.env nodemon ./src/index.js",
"test": "env-cmd ./test.env jest --watch"

server.js:

// Loading deps
const app = express();
...
// Loading middlewares, routes etc.
...
module.exports = app;

index.js:

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

const port = process.env.API_PORT || 5000;

app.listen(port, () => {
    console.log(`Server running on port ${port}`); // eslint-disable-line no-console
});

应用程序正常运行。当我通过supertest测试api时出现错误:

TypeError: Cannot read property 'address' of undefined

enter image description here

app.test.js

const request = require('supertest');
const { app } = require('../src/server');

test('Should render app information', (done) => {
    request(app)
    .get('http://localhost:5000/api/v1/info')
    .expect(200, done);
});

服务器未运行,何时进行测试。我在一些有关Express中api测试主题的教程中了解到了这一点。

我在这里做什么错了?

1 个答案:

答案 0 :(得分:0)

在server.js上:const express=require('express')在吗?然后初始化

const app = express();