server.close 不是函数
Posted
技术标签:
【中文标题】server.close 不是函数【英文标题】:server.close is not a function 【发布时间】:2019-05-29 20:06:30 【问题描述】:我有一个用于测试的超级测试设置,我试图在测试完成后关闭服务器但它抛出错误,它说 server.close() 不是一个函数。这里有什么问题?是快递、开玩笑还是超级测试的问题我无法弄清楚我是测试新手,请帮助我。 server.js 文件:
const next = require('next');
const express = require('express');
const winston = require("winston");
const config = require("config");
const passport = require('passport');
const flash = require('connect-flash');
const path = require('path');
var cookieSession = require('cookie-session');
const cookieParser = require('cookie-parser');
var app = express();
const dev = process.env.NODE_ENV !== 'production';
const nextApp = next(dev);
const port = process.env.PORT || config.get("port");
const handleRequest = nextApp.getRequestHandler();
nextApp.prepare().then(() =>
require("./server/startup/cors")(app);
require("./server/startup/db")();
app.use(cookieParser('ilovescotchscotchyscotchscotch'));
app.use(express.json());
app.use(cookieSession(
name: 'MyAppName',
keys: ['very secret key'],
maxAge: 30 * 24 * 60 * 60 * 1000 // 30 days
));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
require('./server/services/passport')(passport);
require("./server/startup/logging")();
require("./server/startup/routes")(app);
require("./server/startup/prod")(app);
app.get('*', (req, res) =>
return handleRequest(req, res);
);
)
app.listen(port, () => console.log(`Listening at port $port`));
module.exports = app;
这是我的测试文件:
const request = require('supertest');
const User = require('./../../server/models/user');
const mongoose = require('mongoose');
let server ;
beforeEach(() => server = require('./../../server'); );
afterEach(async () =>
await server.close();
);
describe('POST /api/signup', () =>
it('should signin successfully', () =>
)
);
这是我的错误:
TypeError: server.close is not a function
9 | beforeEach(() => server = require('./../../server'); );
10 | afterEach(async () => > 11 | await server.close();
| ^
12 |
13 | );
这里发生了什么?我在这里做错了什么吗?
【问题讨论】:
【参考方案1】:为了关闭服务器,您必须获取从listen
函数返回的实例。在您的示例中,您似乎在这里调用了该函数:
app.listen(port, () => console.log(`Listening at port $port`));
因此,您需要返回实例并关闭它。例如
let appServer = app.listen(port, () => console.log(`Listening at port $port`));
...
appServer.close()
【讨论】:
这对我不起作用,我遵循了建议,但仍然收到错误【参考方案2】:在 index.js 的末尾,您想要导出监听器,而不是应用程序,所以...
app.listen(port, () => console.log(`Listening at port $port`));
module.exports = app;
变成……
const server = app.listen(port, () => console.log(`Listening at port $port`));
module.exports = server;
应该从那里开始工作。
【讨论】:
以上是关于server.close 不是函数的主要内容,如果未能解决你的问题,请参考以下文章