简体   繁体   English

如何为 chai request() 导入服务器应用程序?

[英]how to import server app for chai request()?

I want to run tests on my node express server however this application is starting the server like this:我想在我的 node express 服务器上运行测试,但是这个应用程序正在像这样启动服务器:

createServer()
.then(server => {
    server.listen(PORT);
    Log.info(`Server started on http://localhost:${PORT}`);
})
.catch(err => {
    Log.error("Startup failure.", { error: err });
    process.exit(1);
});

and I know the chai.request() needs to have a parameter that is pointing toward the server app, how can I export/import this createServer() function and pass it in the request method of the chai object?我知道chai.request()需要有一个指向服务器应用程序的参数,我如何导出/导入这个createServer() function 并将其传递给 chai object 的请求方法?

You can use require.main to distinguish between your files being run directly by Node or imported as modules.您可以使用require.main来区分您的文件是由 Node 直接运行还是作为模块导入。

When a file is run directly from Node.js, require.main is set to its module.当一个文件直接从 Node.js 运行时, require.main被设置为其模块。 That means that it is possible to determine whether a file has been run directly by testing require.main === module .这意味着可以通过测试require.main === module来确定文件是否已直接运行。

Eg例如

server.js : server.js

const express = require('express');

const PORT = 3000;
async function createServer() {
  const app = express();
  app.get('/', (req, res) => {
    res.send('hello world');
  });
  return app;
}

if (require.main === module) {
  createServer()
    .then((server) => {
      server.listen(PORT);
      console.info(`Server started on http://localhost:${PORT}`);
    })
    .catch((err) => {
      console.error('Startup failure.', { error: err });
      process.exit(1);
    });
}

module.exports = { createServer };

When you import the createServer from the server.js file, the if statement block will not execute.当您从server.js文件导入createServer时, if语句块将不会执行。 Because you want to create the server instance in the test case.因为要在测试用例中创建服务器实例。

server.test.js : server.test.js

const { createServer } = require('./server');
const chai = require('chai');
const chaiHTTP = require('chai-http');
const { expect } = require('chai');
chai.use(chaiHTTP);

describe('70284767', () => {
  it('should pass', async () => {
    const server = await createServer();
    chai
      .request(server)
      .get('/')
      .end((err, res) => {
        expect(err).to.be.null;
        expect(res.text).to.be.equal('hello world');
      });
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM