我测试的是:一个快速服务器端点
我的目标:在单个脚本中自动化 API 测试
我做什么:我在 NodeJS 子进程中启动 express 服务器,并希望在运行测试套件之前等待它启动(frisby.js 端点测试)
什么不按预期工作:在 Promise 解决之前启动测试套件
wait-on
一旦资源可用,我依赖服务器轮询和解析的包。
const awaitServer = async () => {
await waitOn({
resources: [`http://localhost:${PORT}`],
interval: 1000,
}).then(() => {
console.log('Server is running, launching test suite now!');
});
};
该函数在 startServer 函数中使用:
const startServer = async () => {
console.log(`Launching server http://localhost:${PORT} ...`);
// npmRunScripts is a thin wrapper around child_process.exec to easily access node_modules/.bin like in package.json scripts
await npmRunScripts(
`cross-env PORT=${PORT} node -r ts-node/register -r dotenv/config src/index.ts dotenv_config_path=.env-tests`
);
await awaitServer();
}
最后,我在类似的地方使用它
describe('Endpoints' () => {
beforeAll(startTestServer);
// describes and tests here ...
});
无论如何,当我启动 jest 时,'Server is running, launching test suite now!'
console.log 永远不会出现,并且测试套件失败(因为服务器尚未运行)。为什么 jest 开始测试awaitServer
显然还没有解决?
该npmRunScripts
功能工作正常,因为测试服务器在测试失败后启动并运行了一小会儿。为了这个问题,npmRunScripts 是这样解决的:
// From https://humanwhocodes.com/blog/2016/03/mimicking-npm-script-in-node-js/
const { exec } = require('child_process');
const { delimiter, join } = require('path');
const env = { ...process.env };
const binPath = join(__dirname, '../..', 'node_modules', '.bin');
env.PATH = `${binPath}${delimiter}${env.PATH}`;
/**
* Executes a CLI command with `./node_modules/.bin` in the scope like you
* would use in the `scripts` sections of a `package.json`
* @param cmd The actual command
*/
const npmRunScripts = (cmd, resolveProcess = false) =>
new Promise((resolve, reject) => {
if (typeof cmd !== 'string') {
reject(
new TypeError(
`npmRunScripts Error: cmd is a "${typeof cmd}", "string" expected.`
)
);
return;
}
if (cmd === '') {
reject(
new Error(`npmRunScripts Error: No command provided (cmd is empty).`)
);
return;
}
const subProcess = exec(
cmd,
{ cwd: process.cwd(), env }
);
if (resolveProcess) {
resolve(subProcess);
} else {
const cleanUp = () => {
subProcess.stdout.removeAllListeners();
subProcess.stderr.removeAllListeners();
};
subProcess.stdout.on('data', (data) => {
resolve(data);
cleanUp();
});
subProcess.stderr.on('data', (data) => {
reject(data);
cleanUp();
});
}
});
module.exports = npmRunScripts;