如何通过Jest测试访问通过child_process启动的Express服务器

时间:2020-04-07 21:15:21

标签: express jestjs

我有一个Jest测试,尝试命中和终结点,该测试是通过pre_all函数通过child_process启动的,但它认为在该端口上没有监听的东西。 Jest测试也没有完成,因为child_process忽略了Jest父级的结束愿望。

开玩笑:

const jquery = require('jquery');
const { fork } = require('child_process');

var forked = null;

beforeAll(() => {

    forked = fork('server.js', { silent: true });
    forked.stdout.on('data', function (chunk) {
        console.log("Stdout in child: " + chunk);
    });
});


test('is it ok', () => {
    jquery.ajax({
        async: false,
        type: "GET",
        url: "http://localhost:8765/is-it-ok",
        dataType: "xml",
        success: function (doc, code, response) {
            expect(response.responseText).toBe("ok");
        },
        error: function (data, textStatus, errorThrown) {
            throw new Error('server badness');
        }
    });
});

server.js:

const express = require('express');
var cors = require('cors');
const app = express();
app.use(cors());
const port = 8765;
var server;

app.get('/*', (req, res) => {
    res.send("ok");
});

server = app.listen(port, 'localhost', () => console.log(`Example app listening at http://localhost:${port}`));

server.js本身就可以正常工作,但似乎不是通过Jest控制下的child_process来完成的。这些是不兼容的技术吗?

回购https://github.com/paul-hammant/wtf拥有整个项目。

0 个答案:

没有答案