首页 > 解决方案 > 当 express 应用程序位于函数内部时,如何在 nodejs 中模拟 express?

问题描述

我有httpListener.ts,看起来像这样:

export function startListening() {
     const app = express();
     app
         .use(bodyParser.json())
         .post('/home/about', func1)
         .get('/user/product/:id', func2)
         .use(function (req, res) {
             res.status(404).send(`no routing for path ${req.url}`);
         })
         .listen(httpListenerConfig.port, () => {
             console.log('listening..');
         });
 }

我必须为func1and编写单元测试func2(这些函数是私有的),我想使用假 http 请求来调用它们。

任何想法?

标签: node.jsunit-testingexpressmocha.jssinon

解决方案


您可以使用 superTest 之类的框架来测试 http 请求。SuperTest 需要 express 应用程序,因此我正在导出该应用程序。我将 app.listen 分配给服务器,以便在测试后关闭服务器(server.close)。

httpListener.js

var express = require('express');
function startListening() {
    const app = express();
    app
        .get('/home/about', func1)
        .get('/user/product/:id', func2)
        .use(function (req, res) {
            res.status(404).send(`no routing for path ${req.url}`);
        })
        var server = app.listen(3001, () => {  //so the server can be closed after the test
            console.log('listening..');
        });
        module.exports = server; 
}
function func1 (req, res) {
    res.status(200).send('this is home - about page');
}
  function func2 (req, res) {
    res.status(200).send('this is product page');
}

startListening();

httpListener-test.js

var request = require('supertest');
describe('loading express', function () {
  var server;
  beforeEach(function () {
    server = require('./httpListner.js');
  });
  afterEach(function () {
    server.close();
  });
  it('responds to /home/about', function test(done) {
    request(server)
    .get('/home/about')
    .expect(200) //test status
    .expect('this is home - about page', done); //test the response string
  });
});

要在 func1 和 func2 上进行更多测试,您必须将它们导出以便可以进行测试。


推荐阅读