我正在尝试为React-Native项目设置持续集成,并在端到端测试中遇到一些问题,尤其是在Metro捆绑器周围。
在这种情况下,使用react-native脚本似乎不可靠:
我想编写一个自定义脚本,该脚本可以启动Metro,在服务器准备就绪后运行测试,最后停止服务器以清理环境。
答案 0 :(得分:1)
都市捆绑器必须作为单独的进程运行,以便能够处理请求。做到这一点的方法是使用Child Process : Spawn并保持返回的对象正确清理。
这是一个基本脚本,可同时启动Metro和Gradle,并根据它们的日志输出等到两者准备就绪。
'use strict';
const cp = require('child_process');
const fs = require('fs');
const readline = require('readline');
// List of sub processes kept for proper cleanup
const children = {};
async function asyncPoint(ms, callback = () => {}) {
return await new Promise(resolve => setTimeout(() => {
resolve(callback());
}, ms));
}
async function fork(name, cmd, args, {readyRegex, timeout} = {}) {
return new Promise((resolve) => {
const close = () => {
delete children[name];
resolve(false);
};
if(timeout) {
setTimeout(() => close, timeout);
}
const child = cp.spawn(
cmd,
args,
{
silent: false,
stdio: [null, 'pipe', 'pipe'],
},
);
child.on('close', close);
child.on('exit', close);
child.on('error', close);
const output = fs.createWriteStream(`./volatile-build-${name}.log`);
const lineCb = (line) => {
console.log(`[${name}] ${line}`);
output.write(line+'\n');
if (readyRegex && line.match(readyRegex)) {
resolve(true);
}
};
readline.createInterface({
input: child.stdout,
}).on('line', lineCb);
readline.createInterface({
input: child.stderr,
}).on('line', lineCb);
children[name] = child;
});
}
async function sighandle() {
console.log('\nClosing...');
Object.values(children).forEach(child => child.kill('SIGTERM'));
await asyncPoint(1000);
process.exit(0);
}
function setSigHandler() {
process.on('SIGINT', sighandle);
process.on('SIGTERM', sighandle);
}
async function main() {
setSigHandler();
// Metro Bundler
const metroSync = fork(
'metro',
process.argv0,
[ // args
'./node_modules/react-native/local-cli/cli.js',
'start',
],
{ // options
readyRegex: /Loading dependency graph, done./,
timeout: 60000,
}
);
// Build APK
const buildSync = fork(
'gradle',
'./android/gradlew',
[ // args
`--project-dir=${__dirname}/android`,
'assembleDebug',
],
{ // options
readyRegex: /BUILD SUCCESSFUL/,
timeout: 300000,
}
);
if (await metroSync && await buildSync) {
// TODO: Run tests here
}
sighandle();
}
main();