---
title: 与 Jest 一起使用
---

来源：https://mikro-orm.io/docs/usage-with-jest

当测试你自己使用 [Jest](https://jestjs.io/) 做测试、并用 MikroORM 做数据库的代码时，有几件事需要考虑。

<a id="using-fake-timers"></a>
## 使用假定时器

Jest 允许使用[定时器 mock](https://jestjs.io/docs/timer-mocks)，在测试应用中与时间敏感相关的逻辑时，这是一项非常有用的特性。确保数据库中基于时间的数据准确，同样属于这类测试的一部分。

不过要注意一个坑：Jest 会伪造的函数之一是 [`process.nextTick()`](https://nodejs.org/docs/latest/api/process.html#processnexttickcallback-args)，而 MikroORM 的某些依赖恰好会用到这个函数。

如果你知道自己的代码对事件循环的 tick 推进并不敏感（而可能只对系统时钟敏感），那么可以安全地让 Jest 不伪造这个函数：

```typescript
jest.useFakeTimers({ doNotFake: ['nextTick'] });
```

这样，你仍然可以使用 Jest 定时器 mock API 的其余部分来控制系统时钟，以及你的代码或 MikroORM 中用到的任何定时器（最值得一提的是结果缓存）。

如果你在测试代码中需要对微任务队列有更好的控制，请继续阅读本节余下的内容。

<a id="known-usages-of-processnexttick-by-dependencies"></a>
### 依赖中已知的 `process.nextTick()` 用法

- 所有使用连接池的数据库客户端都依赖一种算法：它们要么在下一个 tick 拿到所请求的连接，要么在请求时没有空闲连接的情况下被排入队列。类似地，释放连接时，如果队列中有请求，就会被调度到下一个 tick 去获取这个被释放的连接，否则连接会被放回池中。
- MongoDB 客户端没有不使用连接池的选项。即便你把池设为一个连接，客户端仍然会去访问那个池，因此需要 `process.nextTick()`。
- MySQL/MariaDB 客户端除了在连接池与池集群中使用 `process.nextTick()` 之外，在完成查询结果时也会用到它。参见 [mysql2 的源码](https://github.com/sidorares/node-mysql2/blob/1d983fa46031a77c689faea5f69e6e0baa1b3de7/lib/commands/query.js#L84-L92)
- PostgreSQL 客户端除了在连接池中使用 `process.nextTick()` 之外，在其非原生客户端处理错误时也会用到它。任何服务端错误（包括例如错误的查询、读取超时等）或用户提供的回调中抛出的异常，都会在下一个 tick 被（重新）抛出。如果你不使用连接池，也不使用原始 SQL 查询，那么应该可以安全地使用被伪造的 `process.nextTick()`，只在手动推进时间时才处理未捕获的异常。
- SQLite 客户端不支持连接池，但它有缓存数据库实例的概念（参见 [sqlite3 文档](https://github.com/TryGhost/node-sqlite3/wiki/Caching)），会在下一个 tick 交出缓存的数据库实例。MikroORM 不使用这一特性，这意味着把 MikroORM 与 SQLite 一起使用始终是安全的。不过，如果你直接获取 SQLite3 客户端并尝试使用缓存实例，就会遇到 SQLite 唯一一处 `process.nextTick()` 的用法。

<a id="allowing-a-real-processnexttick-only-when-required"></a>
### 仅在必要时允许真实的 `process.nextTick()`

如果你确实知道自己需要一个被伪造的 `process.nextTick()`（因为你的代码对微任务队列敏感），但同时又有 MikroORM 搭配连接池或 MySQL，那么你就需要 mock 那些需要 `process.nextTick()` 的部分，让它们只在关键操作期间使用真实函数，并在该关键操作之后恢复为 mock。

这样最终的结果是：你的应用与 MikroORM 相关的代码（flush 前钩子、自定义类型的 JS 到 DB 转换等）可以为下一个 tick 调度所需的内容，但那些回调实际上不会运行。那些回调只会在查询期间、查询结果返回之前被执行（并且可能调度新的 `process.nextTick()` 回调，这些回调可能会也可能不会被执行）。查询结果返回之后，被调度的回调会再次停止执行，直到你手动推进时间。值得注意的是，这也包括在任何 MikroORM 相关代码（flush 后钩子、自定义类型的 DB 到 JS 转换等）期间调度的回调。

要实现这一点，你可以使用类似下面这段代码（在撰写本文时的 Jest 版本上测试可用）：

```ts title='nextTickFixer.ts'
export function wrappedSpy<const T extends {}, const M extends jest.FunctionPropertyNames<Required<T>>>(
  object: T,
  method: T[M] extends jest.Func ? M : never,
  hooks: Readonly<{
    beforeOriginal?: (...args: jest.ArgsType<jest.FunctionProperties<Required<T>>[T[M] extends jest.Func ? M : never]>) => void,
    afterOriginal?: (result: ReturnType<T[M] extends jest.Func ? T[M] : never> extends Promise<infer R> ? R : ReturnType<T[M] extends jest.Func ? T[M] : never>) => void,
    errorOriginal?: (error?: unknown) => void,
  }>
) {
  const originalSpy = jest.spyOn(object, method);
  const mockImpl: Parameters<typeof originalSpy.mockImplementationOnce>[0] = (...args) => {
    hooks.beforeOriginal?.(...args);
    try {
      const result = (object[method] as Function).apply(originalSpy.mock.contexts.at(-1), args);
      if (result instanceof Promise) {
        result.then((v) => {
          hooks.afterOriginal?.(v);
          return v;
        }).catch((e) => {
          hooks.errorOriginal?.(e);
        }).finally(() => {
          originalSpy.mockImplementationOnce(mockImpl!);
        });
      } else {
        hooks.afterOriginal?.(result);
        originalSpy.mockImplementationOnce(mockImpl!);
      }
      return result;
    } catch (e) {
      hooks.errorOriginal?.(e);
      originalSpy.mockImplementationOnce(mockImpl!);
      throw e;
    }
  };
  originalSpy.mockImplementationOnce(mockImpl);
  return originalSpy;
}

const finallyHook = () => {
  jest.useFakeTimers({ doNotFake: [], now: jest.now() });
};

export const fakeTimersHooks = {
  beforeOriginal: () => {
    jest.useFakeTimers({ doNotFake: ['nextTick'], now: jest.now() });
  },
  afterOriginal: finallyHook,
  errorOriginal: finallyHook,
} as const satisfies Parameters<typeof wrappedSpy>[2];
```

<a id="with-mysqlmariadb"></a>
#### 配合 MySQL/MariaDB

如果你使用 MySQL 或 MariaDB，还要加上这段代码来 mock 各个用到 `process.nextTick()` 的方法：

```ts title='fakeTimersFixer.ts'
import { resolve, dirname } from 'node:path';
import { fakeTimersHooks, wrappedSpy } from './nextTickFixer';

export function enableFakeTimersWithMikroOrm() {
  const mysqlDir = dirname(require.resolve('mysql2'));
  return {
    mocks: [
      wrappedSpy(require(resolve(mysqlDir, 'lib/commands/query.js')).prototype, 'done', executeHooks),
      wrappedSpy(require(resolve(mysqlDir, 'lib/commands/ping.js')).prototype, 'pingResponse', executeHooks),
      wrappedSpy(require(resolve(mysqlDir, 'lib/commands/register_slave.js')).prototype, 'registerResponse', executeHooks),
      wrappedSpy(require(resolve(mysqlDir, 'lib/pool.js')).prototype, 'getConnection', executeHooks),
      wrappedSpy(require(resolve(mysqlDir, 'lib/pool.js')).prototype, 'releaseConnection', executeHooks),
      wrappedSpy(require(resolve(mysqlDir, 'lib/pool_cluster.js')).prototype, 'end', executeHooks),
    ],
    mockRestore: function () {
      let mock: jest.SpyInstance | undefined;
      while (mock = this.mocks.pop()) {
        mock.mockRestore();
      }
    }
  };
}
```

<a id="with-postgresql"></a>
#### 配合 PostgreSQL

如果你使用 PostgreSQL，可以考虑把 `pg-native` 加为依赖，这样无需额外 mock 就能处理错误。或者，检查你的测试产生了哪些错误、它们是从哪里抛出的，然后 mock `pg/client.js` 中相应的方法。

无论如何，如果你使用连接池，还需要加上这段：

```ts title='fakeTimersFixer.ts'
import Pool from 'pg-pool';
import { fakeTimersHooks, wrappedSpy } from './nextTickFixer';

export function enableFakeTimersWithMikroOrm() {
  return {
    mocks: [
      wrappedSpy(Pool.prototype, 'connect', executeHooks),
    ],
    mockRestore: function () {
      let mock: jest.SpyInstance | undefined;
      while (mock = this.mocks.pop()) {
        mock.mockRestore();
      }
    }
  };
}
```

<a id="with-mongodb"></a>
#### 配合 MongoDB

如果你使用 MongoDB，请加上这段代码来 mock Mongo 客户端中所有用到 `process.nextTick()` 的方法。

```ts title='fakeTimersFixer.ts'
import { Topology } from 'mongodb/lib/sdam/topology';
import { ConnectionPool } from 'mongodb/lib/cmap/connection_pool';
import { fakeTimersHooks, wrappedSpy } from './nextTickFixer';

function enableFakeTimersWithMikroOrm() {
  return {
    mocks: [
      wrappedSpy(ConnectionPool, 'constructor', fakeTimersHooks),
      wrappedSpy(ConnectionPool.prototype, 'checkIn', fakeTimersHooks),
      wrappedSpy(ConnectionPool.prototype, 'checkOut', fakeTimersHooks),
      wrappedSpy(ConnectionPool.prototype, 'clear', fakeTimersHooks),
      wrappedSpy(ConnectionPool.prototype, 'destroyConnection', fakeTimersHooks),
      wrappedSpy(ConnectionPool.prototype, 'ensureMinPoolSize', fakeTimersHooks),
      wrappedSpy(ConnectionPool.prototype, 'processWaitQueue', fakeTimersHooks),
      wrappedSpy(Topology.prototype, 'serverUpdateHandler', fakeTimersHooks),
      wrappedSpy(Topology.prototype, 'selectServer', fakeTimersHooks),
    ],
    mockRestore: function () {
      let mock: jest.SpyInstance | undefined;
      while (mock = this.mocks.pop()) {
        mock.mockRestore();
      }
    }
  };
}
```

<a id="usage-of-fixed-mocks"></a>
#### 使用修正后的 mock

在你的测试中，在调用任何查询之前先调用 `enableFakeTimersWithMikroOrm`。你可以在返回的对象上调用 `mockRestore()` 来重新启用真实定时器（或者确保一旦调用查询，测试会冻结而不是继续）。例如

```ts title='example.test.ts'
import { initORM } from './db';// 参见 "项目配置"
import { enableFakeTimersWithMikroOrm } from './fakeTimersFixer'; // 依你的驱动而定；见上文

test(() => {
  const orm = initORM({
    // 你的测试配置
  });
  jest.useFakeTimers();
  const ormMock = enableFakeTimersWithMikroOrm();

  // 照常编写你的测试

  ormMock.restoreMock();
  jest.useRealTimers();
});
```
