本页内容

Node.js 拥有灵活且强大的内置测试运行器。本指南将展示如何设置和使用它。

example/
  ├ …
  ├ src/
    ├ app/…
    └ sw/…
  └ test/
    ├ globals/
      ├ …
      ├ IndexedDb.js
      └ ServiceWorkerGlobalScope.js
    ├ setup.mjs
    ├ setup.units.mjs
    └ setup.ui.mjs
npm init -y
npm install --save-dev concurrently
{
  "name": "example",
  "scripts": {
    "test": "concurrently --kill-others-on-fail --prefix none npm:test:*",
    "test:sw": "node --import ./test/setup.sw.mjs --test './src/sw/**/*.spec.*'",
    "test:units": "node --import ./test/setup.units.mjs --test './src/app/**/*.spec.*'",
    "test:ui": "node --import ./test/setup.ui.mjs --test './src/app/**/*.test.*'"
  }
}

注意:glob 需要 node v21+,并且 glob 本身必须用引号包裹(否则行为会与预期不同,起初可能看似正常,实则不然)。

有些内容是始终需要的,可以把它们放在如下的基础设置文件中。该文件会被其他更专用的设置文件导入。

`test/setup.mjs`
import { register } from 'node:module';

register('some-typescript-loader');
// 此后即可支持 TypeScript
// 但其他 test/setup.*.mjs 文件仍必须是纯 JavaScript!

然后为每种设置创建一个专用的 setup 文件(确保每个文件中都导入基础的 setup.mjs)。隔离这些设置有多种原因,但最明显的是 YAGNI 和性能:你设置的内容中很多是特定环境的 mock/stub,它们可能开销很大,会拖慢测试运行。当不需要时,你希望避免这些成本(比如支付给 CI 的实际费用、等待测试完成的时间等)。

下面的每个示例都来自真实项目;它们可能不适合或不适用于你的项目,但都展示了广泛适用的通用概念。

有时你可能希望动态生成测试用例。例如,你想在一堆文件上测试同一件事。这是可以做到的,只是略显晦涩。你必须使用 test(不能使用 describe)以及 testContext.test:

import assert from 'node:assert/strict';
import { test } from 'node:test';

import { detectOsInUserAgent } from '…';

const userAgents = [
  {
    ua: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.3',
    os: 'WIN',
  },
  // …
];

test('Detect OS via user-agent', { concurrency: true }, t => {
  for (const { os, ua } of userAgents) {
    t.test(ua, () => assert.equal(detectOsInUserAgent(ua), os));
  }
});
import assert from 'node:assert/strict';
import { test } from 'node:test';

import { detectOsInUserAgent } from '…';

const userAgents = [
  { ua: '…', os: 'WIN' },
  // …
];

test('Detect OS via user-agent', { concurrency: true }, async t => {
  const cases = userAgents.map(({ os, ua }) => {
    t.test(ua, () => assert.equal(detectOsInUserAgent(ua), os));
  });

  await Promise.allSettled(cases);
});
import assert from 'node:assert/strict';
import { test } from 'node:test';

import { getWorkspacePJSONs } from './getWorkspacePJSONs.mjs';

const requiredKeywords = ['node.js', 'sliced bread'];

test('Check package.jsons', { concurrency: true }, async t => {
  const pjsons = await getWorkspacePJSONs();

  for (const pjson of pjsons) {
    // ⚠️ 要用 `t.test`,不是 `test`
    t.test(`Ensure fields are properly set: ${pjson.name}`, () => {
      assert.partialDeepStrictEqual(pjson.keywords, requiredKeywords);
    });
  }
});
import assert from 'node:assert/strict';
import { test } from 'node:test';

import { getWorkspacePJSONs } from './getWorkspacePJSONs.mjs';

const requiredKeywords = ['node.js', 'sliced bread'];

test('Check package.jsons', { concurrency: true }, async t => {
  const pjsons = await getWorkspacePJSONs();

  const cases = pjsons.map(pjson =>
    // ⚠️ 要用 `t.test`,不是 `test`
    t.test(`Ensure fields are properly set: ${pjson.name}`, () => {
      assert.partialDeepStrictEqual(pjson.keywords, requiredKeywords);
    })
  );

  // 让这些用例并发运行。
  await Promise.allSettled(cases);
});
import { globSync } from 'node:fs';
import { fileURLToPath } from 'node:url';

// 注意:这里最好实现为异步生成器,利用 fs.glob(而不是 fs.globSync);
// 然而,生成器尤其是异步生成器理解起来要困难得多,
// 因此这里提供一个简化的示例,便于理解。

/**
 * 获取所有 package.json 文件,默认只遍历 ./workspaces/ 下一层
 */
export function getWorkspacePJSONs(path = './workspaces/*/package.json') {
  return Promise.all(
    globSync(
      // ⚠️ 传入文件 URL 字符串(比如来自 import.meta.resolve 的)会导致 glob* 静默失败
      fileURLToPath(import.meta.resolve(path))
    ).map(path => import(path, { with: { type: 'json' } }))
  );
}

注意:在 23.8.0 版本之前,设置方式截然不同,因为 testContext.test 不会自动被等待。

ServiceWorkerGlobalScope 包含一些其他环境中不存在的非常特定的 API,其中某些 API 看起来与其他 API 相似(例如 fetch),但行为有所增强。你不希望这些 API 泄漏到无关的测试中。

`test/setup.sw.mjs`
import { beforeEach } from 'node:test';

import { ServiceWorkerGlobalScope } from './globals/ServiceWorkerGlobalScope.js';

import './setup.mjs'; // 💡

beforeEach(globalSWBeforeEach);
function globalSWBeforeEach() {
  globalThis.self = new ServiceWorkerGlobalScope();
}
import assert from 'node:assert/strict';
import { describe, mock, it } from 'node:test';

import { onActivate } from './onActivate.js';

describe('ServiceWorker::onActivate()', () => {
  const globalSelf = globalThis.self;
  const claim = mock.fn(async function mock__claim() {});
  const matchAll = mock.fn(async function mock__matchAll() {});

  class ActivateEvent extends Event {
    constructor(...args) {
      super('activate', ...args);
    }
  }

  before(() => {
    globalThis.self = {
      clients: { claim, matchAll },
    };
  });
  after(() => {
    global.self = globalSelf;
  });

  it('should claim all clients', async () => {
    await onActivate(new ActivateEvent());

    assert.equal(claim.mock.callCount(), 1);
    assert.equal(matchAll.mock.callCount(), 1);
  });
});

快照测试由 Jest 推广开来;如今许多库都实现了这种功能,包括从 v22.3.0 起的 Node.js。它有多种用例,例如验证组件渲染输出和基础设施即代码配置。无论用例如何,概念都是一样的。

除了通过 --experimental-test-snapshots启用该功能外,没有_必需_的特定配置。不过为了演示可选配置,你可能会在现有测试配置文件中添加如下内容。

`test/setup.ui.mjs`

默认情况下,node 生成的文件名无法被语法高亮检测识别:.js.snapshot。生成的文件实际上是 CJS 文件,因此更合适的文件名应以 .snapshot.cjs 结尾(或者更简洁的 .snap.cjs,如下);这在 ESM 项目中也能更好地处理。

import { basename, dirname, extname, join } from 'node:path';
import { snapshot } from 'node:test';

snapshot.setResolveSnapshotPath(generateSnapshotPath);
/**
 * @param {string} testFilePath '/tmp/foo.test.js'
 * @returns {string} '/tmp/foo.test.snap.cjs'
 */
function generateSnapshotPath(testFilePath) {
  const ext = extname(testFilePath);
  const filename = basename(testFilePath, ext);
  const base = dirname(testFilePath);

  return join(base, `${filename}.snap.cjs`);
}

下面的示例演示如何使用 testing library 对 UI 组件进行快照测试;注意访问 assert.snapshot 的两种不同方式:

import { describe, it } from 'node:test';

import { prettyDOM } from '@testing-library/dom';
import { render } from '@testing-library/react'; // 任意框架(例如 svelte)

import { SomeComponent } from './SomeComponent.jsx';

describe('<SomeComponent>', () => {
  // 对于偏好“胖箭头”语法的人,下面这种写法在一致性上可能更好
  it('should render defaults when no props are provided', t => {
    const component = render(<SomeComponent />).container.firstChild;

    t.assert.snapshot(prettyDOM(component));
  });

  it('should consume `foo` when provided', function () {
    const component = render(<SomeComponent foo="bar" />).container.firstChild;

    this.assert.snapshot(prettyDOM(component));
    // `this` 只有在使用 `function` 时才有效(不适用于“胖箭头”)。
  });
});

⚠️ assert.snapshot 来自测试的上下文(t 或 this),而不是 node:assert。这是必要的,因为测试上下文可以访问 node:assert 无法访问的作用域(否则每次使用 assert.snapshot 时都得手动提供它,比如 snapshot(this, value),相当繁琐)。

单元测试是最简单的测试,通常几乎不需要特殊设置。绝大多数测试很可能都是单元测试,因此保持这一设置尽可能精简非常重要:设置性能哪怕稍微下降,也会被放大并产生连锁影响。

`test/setup.units.mjs`
import { register } from 'node:module';

import './setup.mjs'; // 💡

register('some-plaintext-loader');
// 现在可以导入像 graphql 这样的纯文本文件:
// import GET_ME from 'get-me.gql'; GET_ME = '
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';

import { Cat } from './Cat.js';
import { Fish } from './Fish.js';
import { Plastic } from './Plastic.js';

describe('Cat', () => {
  it('should eat fish', () => {
    const cat = new Cat();
    const fish = new Fish();

    assert.doesNotThrow(() => cat.eat(fish));
  });

  it('should NOT eat plastic', () => {
    const cat = new Cat();
    const plastic = new Plastic();

    assert.throws(() => cat.eat(plastic));
  });
});

UI 测试通常需要 DOM,可能还需要其他浏览器特有的 API(例如下面使用的 IndexedDb)。这些测试的设置往往非常复杂且开销很大。

`test/setup.ui.mjs`

如果你使用像 IndexedDb 这样但非常孤立的 API,下面这种全局 mock 或许并非良策。相反,也许可以把这个 beforeEach 移到实际访问 IndexedDb 的具体测试中。注意,如果访问 IndexedDb(或其他东西)的模块本身被广泛使用,要么 mock 那个模块(可能是更好的选择),要么_确实_把它保留在这里。

import { register } from 'node:module';

// ⚠️ 确保只实例化一个 JSDom 实例;多个实例会导致很多麻烦 🤬
import jsdom from 'global-jsdom';

import './setup.units.mjs'; // 💡

import { IndexedDb } from './globals/IndexedDb.js';

register('some-css-modules-loader');

jsdom(undefined, {
  url: 'https://test.example.com', // ⚠️ 不指定这一项很可能带来很多麻烦 🤬
});

// 如何装饰全局对象的示例。
// JSDOM 的 `history` 不处理导航;下面的代码能处理大多数情况。
const pushState = globalThis.history.pushState.bind(globalThis.history);
globalThis.history.pushState = function mock_pushState(data, unused, url) {
  pushState(data, unused, url);
  globalThis.location.assign(url);
};

beforeEach(globalUIBeforeEach);
function globalUIBeforeEach() {
  globalThis.indexedDb = new IndexedDb();
}

UI 测试可以有两个不同层次:类似单元测试的层次(外部依赖都被 mock)和更接近端到端的层次(只 mock IndexedDb 等外部依赖,其余链路都是真实的)。前者通常更纯粹,后者通常交给借助 Playwright 或 Puppeteer 等工具完成的完整端到端自动化可用性测试。下面是前者的示例。

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

import { screen } from '@testing-library/dom';
import { render } from '@testing-library/react'; // 任意框架(例如 svelte)

// ⚠️ 注意 SomeOtherComponent 不是静态导入;
// 这是为了便于 mock 它自身的导入。

describe('<SomeOtherComponent>', () => {
  let SomeOtherComponent;
  let calcSomeValue;

  before(async () => {
    // ⚠️ 顺序很重要:必须先设置 mock,再导入使用它的模块。

    // 需要设置 `--experimental-test-module-mocks`。
    calcSomeValue = mock.module('./calcSomeValue.js', {
      calcSomeValue: mock.fn(),
    });

    ({ SomeOtherComponent } = await import('./SomeOtherComponent.jsx'));
  });

  describe('when calcSomeValue fails', () => {
    // 这种情况你不希望用快照来处理,因为那会很脆弱:
    // 当对错误消息做一些无关紧要的更新时,
    // 快照测试会错误地失败
    // (而且更新快照也没有实际意义)。

    it('should fail gracefully by displaying a pretty error', () => {
      calcSomeValue.mockImplementation(function mock__calcSomeValue() {
        return null;
      });

      render(<SomeOtherComponent />);

      const errorMessage = screen.queryByText('unable');

      assert.ok(errorMessage);
    });
  });
});