本页内容

模拟(mocking)是一种创建替身、傀儡的手段。通常以“当 'a' 时,做 'b'”的方式操控。其思路是减少活动部件的数量,并控制那些“无关紧要”的东西。“mock”和“stub”在技术上是两种不同的“测试替身”。对于好奇的读者:stub 是一个什么都不做(空操作)但会记录调用情况的替代品;mock 则是带有假实现的 stub(即“当 'a' 时,做 'b'”)。在本文中,两者的区别并不重要,stub 也统称为 mock。

测试应当是确定性的:可以按任意顺序、任意次数运行,并且始终产生相同的结果。恰当的设置和模拟使这成为可能。

Node.js 提供了多种方式来模拟各种代码片段。

本文讨论以下类型的测试:

类型描述示例可模拟对象
单元测试可隔离的最小代码片段const sum = (a, b) => a + b自己的代码、外部代码、外部系统
组件测试一个单元及其依赖const arithmetic = (op = sum, a, b) => ops[op](a, b)外部代码、外部系统
集成测试多个组件组合在一起-外部代码、外部系统
端到端(e2e)测试应用 + 外部数据存储、交付等一个假用户(例如 Playwright 代理)实际使用连接到真实外部系统的应用。无(不要模拟)

关于何时模拟、何时不模拟存在不同流派,下面概述其大致观点。

主要有 3 类可模拟对象:

  • 自己的代码
  • 外部代码
  • 外部系统

这是你的项目所能控制的代码。

import foo from './foo.mjs';

export function main() {
  const f = foo();
}

这里,foo 是 main 的一个“自己的代码”依赖。

要对 main 做真正的单元测试,就应该模拟 foo:你测试的是 main 是否正常工作,而不是 main + foo 是否正常工作(那是另一种测试)。

模拟 foo 可能弊大于利,尤其当 foo 简单、测试充分且很少更新时。

不模拟 foo 可能更好,因为更真实,也能提高 foo 的覆盖率(因为 main 的测试也会验证 foo)。不过这也可能带来噪音:当 foo 出问题时,一大堆其他测试也会失败,排查问题就更繁琐:如果只有最终导致问题的那一个测试失败,很容易发现;而有 100 个测试失败时,就像大海捞针一样难以找到真正的问题。

这是你的项目无法控制的代码。

import bar from 'bar';

export function main() {
  const f = bar();
}

这里,bar 是一个外部包,例如 npm 依赖。

毫无争议的是,对于单元测试,这始终应该被模拟。对于组件测试和集成测试,是否模拟则取决于它是什么。

验证你的项目不维护的代码是否正常工作,并不是单元测试的目标(那些代码应该有自己的测试)。

有时,模拟根本不现实。例如,你几乎不会去模拟 react 或 angular 这样的大型框架(那样做弊大于利)。

这些是数据库、环境(Web 应用的 Chromium 或 Firefox、Node 应用的操作系统等)、文件系统、内存存储等。

理想情况下,不需要模拟这些。除了以某种方式为每个用例创建隔离副本(由于成本、额外执行时间等原因通常非常不切实际)之外,次优选择就是模拟。如果不模拟,测试会互相破坏:

import { db } from 'db';

export function read(key, all = false) {
  validate(key);

  if (all) {
    return db.getAll(key);
  }

  return db.getOne(key);
}

export function save(key, val) {
  validate(key, val);

  return db.upsert(key, val);
}
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';

import { db } from 'db';

import { read, save } from './storage.mjs';

describe('storage', { concurrency: true }, () => {
  it('should retrieve the requested item', async () => {
    await db.upsert('good', 'item'); // 给它一些可读的数据
    await db.upsert('erroneous', 'item'); // 给它一个失败的机会

    const results = await read('a', true);

    assert.equal(results.length, 1); // 确保 read 没有取到 erroneous 项

    assert.deepEqual(results[0], { key: 'good', val: 'item' });
  });

  it('should save the new item', async () => {
    const id = await save('good', 'item');

    assert.ok(id);

    const items = await db.getAll();

    assert.equal(items.length, 1); // 确保 save 没有创建重复项

    assert.deepEqual(items[0], { key: 'good', val: 'item' });
  });
});

在上面代码中,第一个和第二个用例(it() 语句)会互相破坏,因为它们并发运行并修改同一个存储(竞态条件):save() 的插入可能导致本来正确的 read() 测试在断言找到的条目时失败(read() 也可能对 save() 造成同样的影响)。

这里利用 Node.js 测试运行器中的 mock。

import assert from 'node:assert/strict';
import { before, describe, it, mock } from 'node:test';

describe('foo', { concurrency: true }, () => {
  const barMock = mock.fn();
  let foo;

  before(async () => {
    const barNamedExports = await import('./bar.mjs')
      // 丢弃原来的默认导出
      .then(({ default: _, ...rest }) => rest);

    // 通常不必在每次之后手动调用 restore()
    // 也不必在全部之后调用 reset()(node 会自动处理)。
    mock.module('./bar.mjs', {
      defaultExport: barMock,
      // 保留其他你不想模拟的导出。
      namedExports: barNamedExports,
    });

    // 这里必须使用动态导入,因为这是确保
    // 导入在 mock 设置之后才开始的唯一方式。
    ({ foo } = await import('./foo.mjs'));
  });

  it('should do the thing', () => {
    barMock.mock.mockImplementationOnce(function bar_mock() {
      /* … */
    });

    assert.equal(foo(), 42);
  });
});

一个鲜为人知的事实是,有一种内置方式可以模拟 fetch。undici 是 Node.js 中 fetch 的实现。它随 node 一起提供,但目前没有由 node 自身暴露,因此需要安装(例如 npm install undici)。

import assert from 'node:assert/strict';
import { beforeEach, describe, it } from 'node:test';

import { MockAgent, setGlobalDispatcher } from 'undici';

import endpoints from './endpoints.mjs';

describe('endpoints', { concurrency: true }, () => {
  let agent;
  beforeEach(() => {
    agent = new MockAgent();
    setGlobalDispatcher(agent);
  });

  it('should retrieve data', async () => {
    const endpoint = 'foo';
    const code = 200;
    const data = {
      key: 'good',
      val: 'item',
    };

    agent
      .get('https://example.com')
      .intercept({
        path: endpoint,
        method: 'GET',
      })
      .reply(code, data);

    assert.deepEqual(await endpoints.get(endpoint), {
      code,
      data,
    });
  });

  it('should save data', async () => {
    const endpoint = 'foo/1';
    const code = 201;
    const data = {
      key: 'good',
      val: 'item',
    };

    agent
      .get('https://example.com')
      .intercept({
        path: endpoint,
        method: 'PUT',
      })
      .reply(code, data);

    assert.deepEqual(await endpoints.save(endpoint), {
      code,
      data,
    });
  });
});

像奇异博士一样,你也能控制时间。这么做通常只是为了方便,避免人为拉长测试运行时间(你真的愿意等 3 分钟让那个 setTimeout() 触发吗?)。你可能还想在时间中穿梭。这里利用 Node.js 测试运行器中的 mock.timers。

注意这里使用了时区(时间戳中的 Z)。忽略一致的时区很可能导致意外结果。

import assert from 'node:assert/strict';
import { describe, it, mock } from 'node:test';

import ago from './ago.mjs';

describe('whatever', { concurrency: true }, () => {
  it('should choose "minutes" when that\'s the closet unit', () => {
    mock.timers.enable({ now: new Date('2000-01-01T00:02:02Z') });

    const t = ago('1999-12-01T23:59:59Z');

    assert.equal(t, '2 minutes ago');
  });
});

这在跟静态固定数据(已提交到仓库中的数据)做比较时尤其有用,例如快照测试。