如何在量角器运行之前启动服务器并在之后进行清理 [英] How to start a server before protractor runs and clean up afterwards
问题描述
似乎量角器没有提供任何开箱即用的解决方案来在运行之前启动服务器.在运行功能测试之前必须运行多个命令是一种糟糕的用户体验,并且不利于自动化测试.
It seems protractor doesn't provide any out of the box solution for starting a server before it runs. Having to run multiple commands before functional tests will run is a bad user experience and bad for automated testing.
Angular-cli 有它自己的相当复杂的解决方案,这个插件声称可以复制它,尽管它对我不起作用并且可能没有维护.https://www.npmjs.com/package/protractor-webpack
Angular-cli has its own solution that is rather complicated, which this plugin claims to duplicate, although it doesn't work for me and may be unmaintained. https://www.npmjs.com/package/protractor-webpack
下面接受更好的解决方案
BETTER SOLUTION ACCEPTED BELOW
我想出了一个使用 child_process.exec 的解决方案,虽然我不太喜欢它,但它似乎运行良好.我想分享它,以防有人需要它,看看是否有人能提出更好的解决方案.
I came up with a solution using child_process.exec that seems to work well, although I don't like it very much. I'd like to share it in case anyone needs it and to see if anyone can come up with a better solution.
在量角器的 beforeLaunch 钩子中启动进程:
Launch the process in the beforeLaunch hook of protractor:
beforeLaunch: () => {
webpackServerProcess = exec(`webpack-dev-server --port=3003 --open=false`, null, () => {
console.log(`Webpack Server process reports that it exited. Its possible a server was already running on port ${port}`)
});
},
然后在配置块上方,我们设置退出处理程序以确保服务器在我们完成后被杀死.
Then above the configuration block we set up the exit handlers to make positively sure that server gets killed when we are done.
let webpackServerProcess; // Set below in beforeLaunch hook
function cleanUpServer(eventType) {
console.log(`Server Cleanup caught ${eventType}, killing server`);
if (webpackServerProcess) {
webpackServerProcess.kill();
console.log(`SERVER KILLED`);
}
}
[`exit`, `SIGINT`, `SIGUSR1`, `SIGUSR2`, `uncaughtException`].forEach((eventType) => {
process.on(eventType, cleanUpServer.bind(null, eventType));
})
需要各种事件监听器来处理cntrl+c事件和进程被ID杀死的情况.奇怪的是,该节点没有提供包含所有这些的事件.
The various event listeners are needed to handle cntrl+c events and situations where the process is killed by ID. Strange that node does not provide an event to encompass all of these.
推荐答案
我找到了一种使用 webpack-dev-server 节点 api 的更可靠的方法.这样就不会产生单独的进程,我们也不必清理任何东西.此外,它会阻止量角器,直到 webpack 准备就绪.
I found a much more reliable way to do it using the webpack-dev-server node api. That way no separate process is spawned and we don't have to clean anything. Also, it blocks protractor until webpack is ready.
beforeLaunch: () => {
return new Promise((resolve, reject) => {
new WebpackDevServer(webpack(require('./webpack.config.js')()), {
// Do stuff
}).listen(APP_PORT, '0.0.0.0', function(err) {
console.log('webpack dev server error is ', err)
resolve()
}).on('error', (error) => {
console.log('dev server error ', error)
reject(error)
})
})
},
这篇关于如何在量角器运行之前启动服务器并在之后进行清理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!