server.close不是函数

时间:2019-01-03 08:38:55

标签: express jestjs supertest

我有一个用于测试的超级测试设置,我试图在测试完成后关闭服务器,但它会抛出错误,这是说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 |   });

这是怎么回事?我在这里做错了什么吗?

2 个答案:

答案 0 :(得分:1)

在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;

应该从那里开始工作。

答案 1 :(得分:0)

为了关闭服务器,必须获取从listen函数返回的实例。在您的示例中,您似乎在这里调用了该函数:

app.listen(port, () => console.log(`Listening at port ${port}`));

因此,您需要将实例返回并关闭该实例。例如

let appServer = app.listen(port, () => console.log(`Listening at port ${port}`));
...
appServer.close()