使用 bindStore() 进行上下文传播


🌐 Context propagation with bindStore()

跟踪通道可以通过绑定一个 AsyncLocalStorage 实例来在测试执行过程中传播上下文。这允许上下文在测试函数及测试中的所有异步操作中自动可用。

🌐 The tracing channel can be used to propagate context through test execution by binding an AsyncLocalStorage instance. This allows context to be automatically available in the test function and all async operations within the test.

import dc from 'node:diagnostics_channel';
import { AsyncLocalStorage } from 'node:async_hooks';

const testStorage = new AsyncLocalStorage();
const testChannel = dc.tracingChannel('node.test');

// Bind context to test execution — the returned value becomes the store
testChannel.start.bindStore(testStorage, (data) => {
  return { testName: data.name, startTime: Date.now() };
});

// Optionally handle errors and cleanup
testChannel.error.subscribe((data) => {
  const store = testStorage.getStore();
  console.log(`Test "${data.name}" failed after ${Date.now() - store.startTime}ms`);
});

testChannel.end.subscribe((data) => {
  const store = testStorage.getStore();
  console.log(`Test "${data.name}" completed in ${Date.now() - store.startTime}ms`);
}); 

在使用 bindStore() 时,提供的上下文将会自动传播到测试函数以及测试中的所有异步操作,无需在测试代码中进行任何额外的处理。

🌐 When using bindStore(), the context provided will be automatically propagated to the test function and all async operations within the test, without requiring any additional instrumentation in the test code.