在每次测试之前运行迁移并回滚它们真的很慢,甚至可能需要几秒钟才能运行。因此,您可能不需要能够并行运行测试以达到足够好的速度。
如果您设置测试的方式是在开始运行测试之前删除/创建/迁移一次,并且在测试之间只截断表中的所有数据并用新数据填充它应该快 10 倍(截断通常需要大约不到 50 毫秒)。您可以轻松截断所有表格,例如使用 knex-db-manager 包。
如果您真的喜欢并行运行 postgresql 测试,那么您需要与运行并行测试一样多的测试数据库。您可以创建测试数据库的“池”(testdb-1、testdb-2、testdb-3,...),并且在每个 jest 测试中,您首先必须从测试数据库池中请求数据库,以便您可以真正运行多个测试同时,它们不会干扰同一个数据库。
最后,在测试数据库中重置数据的另一种非常快速的方法是使用pg-dump / pg-restore 和二进制数据库转储。在某些情况下,它可能比仅运行填充脚本更快或更容易处理。特别是在您在每次测试中使用相同的初始数据的情况下。
通过这种方式,您可以在开始运行测试之前为测试数据库创建初始状态并进行转储。为了转储和恢复,我编写了这些小助手,我可能会在某个时候将其添加到 knex-db-manager。
转储/恢复的参数有点棘手(特别是设置密码),所以这些 sn-ps 可能会有所帮助:
倾销:
shelljs.env.PGPASSWORD = config.knex.connection.password;
const leCommand = [
`pg_dump -a -O -x -F c`,
`-f '${dumpFileName}'`,
`-d ${config.knex.connection.database}`,
`-h ${config.knex.connection.host}`,
`-p ${config.knex.connection.port}`,
`-U ${config.knex.connection.user}`,
].join(' ');
console.log('>>>>>>>> Command started:', leCommand);
shelljs.rm('-f', dumpFileName);
shelljs.exec(leCommand, (code, stdout, stderr) => {
console.log('======= Command ready:', leCommand, 'with exit code:', code);
if (code === 0) {
console.log('dump ready:', stdout);
} else {
console.log('dump failed:', stderr);
}
});
恢复:
shelljs.env.PGPASSWORD = config.knex.connection.password;
const leCommand = [
`pg_restore -a -O -x -F c`,
`-d ${config.knex.connection.database}`,
`-h ${config.knex.connection.host}`,
`-p ${config.knex.connection.port}`,
`-U ${config.knex.connection.user}`,
`--disable-triggers`,
`'${dumpFileName}'`,
].join(' ');
console.log('>>>>>>>> Command started:', leCommand);
shelljs.exec(leCommand, (code, stdout, stderr) => {
console.log('======= Command ready:', leCommand, 'with exit code:', code);
if (code === 0) {
console.log('restore ready:', stdout);
} else {
console.log('restore failed:', stderr);
}
});