如何与NodeJS,Jest和Knex并行运行Postgres测试?

时间:2017-11-15 14:57:02

标签: node.js postgresql testing jest knex.js

我有一个项目是使用Postgres在生产/暂存和Sqlite开发中开发的。使用Sqlite,我们能够在13秒内并行运行所有测试。

这对于初始开发来说是一个很好的策略,但是有一些事情是Sqlite无法做到的(例如,删除列和添加新的外键)。所以我认为我们应该放弃Sqlite并使用Postgres。

测试套件需要大约一分钟才能运行,如果测试失败,我通常必须手动删除迁移表。它没有提供良好的测试体验。

您对使用NodeJS,Knex和Jest在Postgres数据库上并行运行测试有什么建议吗?

1 个答案:

答案 0 :(得分:2)

在每次测试之前运行迁移并将其回滚非常慢,运行可能需要几秒钟。因此,您可能不需要能够并行运行测试以达到足够快的速度。

如果您设置测试的方式是在开始运行测试之前只删除/创建/迁移一次,并且在测试之间只截断表中的所有数据并用新数据填充它应该快10倍(截断通常需要大约不到50ms)。您可以轻松截断所有表格,例如使用knex-db-manager包。

如果您真的想并行运行postgresql测试,则需要运行并行测试的测试数据库。您可以创建测试数据库的“池”(testdb-1,testdb-2,testdb-3,...),并且在每个jest测试中,您首先必须从测试数据库池中请求数据库,以便您可以真正运行多个测试同时,他们不会干扰同一个数据库。

最后,在测试数据库中重置数据的另一种快速方法是使用pg-dump / pg-restore和二进制数据库转储。在某些情况下,处理群集脚本可能更快或更容易处理。特别是在每个测试中使用相同初始数据的情况下。

通过这种方式,您可以在开始运行测试并转储它之前为测试数据库创建初始状态。对于转储和恢复,我写了这些小助手,我可能会在某些时候添加到knex-db-manager

转储/恢复的参数有点棘手(特别是设置密码)所以这些代码片段可能会有所帮助:

倾倒:

      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);
    }
  });
相关问题