为测试套房提供最无缝的打入依赖性注射方法.
示例
初始化(extern.ts(中文(简体) )
import { initialize } from "@ghostry/extern";
/**
* Initialize an instance of the library with optional configuration.
*/
export const extern = initialize({});
资料来源(source.ts(中文(简体) )
/**
* Import the library from the initialization module.
*/
import { extern } from "./extern.ts";
/**
* The function to be mocked.
*
* For demonstration, it performs some simple math, but it represents an
* interaction with an external system which would not be within the intended
* scope of a unit test.
*/
function computeSomething(x: string) {
return x + " brown";
}
/**
* A function that represents interaction with an external system, but unlike
* the other example function above, this does not return anything useful to the
* calling code.
*/
function doSomething() {
console.log("jumped over the lazy dog");
}
/**
* A library-native type identity (or a Standard Schema) is used to:
*
* 1. Identify the wrapped code block and describe its return type.
* 2. Associate with correctly-typed mocks in a test suite.
*/
export const identity = extern.T<string>();
export function example() {
/**
* Wrap external interactions that produce a value.
*/
const result = extern.typed
.by(identity)
.will(() => computeSomething("quick"));
/**
* Wrap external interactions that perform an effect.
*/
extern.effect.will(doSomething);
return result + " fox";
}
如果您也想在此库中进行数据验证, 请带一个或一个以上选择的 符合标准Schema的验证库,并在源代码中进行这些修改:
/**
* Your chosen validation library.
*/
import * as S from "sury";
/**
* Instead of a library-native type identity, use a schema.
*/
export const identity = S.string;
/**
* Instead of `.typed`, use `.validated`.
*/
const result = extern.validated
.by(identity)
.will(() => computeSomething("quick"));
测试( E)test.ts(中文(简体) )
import { extern } from "./extern.ts";
import { example, identity } from "./source.ts";
import { test, expect } from "bun:test";
test("example test", async () => {
/**
* By default, the function to test will still execute its external
* interaction even though it was wrapped at its source. This prevents
* immediately breaking any existing tests written for the function.
*/
expect(example()).toEqual("quick brown fox");
/**
* Enable dependency-injection style mocking.
*
* This begins tracking uses of `extern` at runtime with their associated
* schema definition.
*
* The `testing` function receives a function to mock uses of `extern` with
* static test data.
*
* It identifies which external interaction to mock by the schema definition
* used. (In many cases, this will be sufficient, but disambiguation is
* possible as necessary.)
*
* Effect blocks (unlike value blocks) do not need to be mocked as they will
* always be skipped. (Spying on them is still possible though.)
*/
await extern.testing((mock) => {
/**
* The mocking data must conform to the schema type. This is enforced by
* TypeScript.
*
* Each mock returns a dedicated spy which can be used later to inspect
* executions that used the mock.
*
* The definition of mocks is the same whether using `typed` or `validated`
* mode.
*/
const spy = mock(identity).with("a");
/**
* The function will not execute the external interactions. Instead, the
* mocked data will be returned in its place. Thus, the result is different,
* as expected.
*/
expect(example()).toEqual("a fox");
/**
* Assertions can be made about the mocked executions that have occurred.
*/
expect(spy.executions).toHaveLength(1);
});
/**
* Outside of the testing block, all wrapped interactions will run normally,
* including effects.
*/
expect(example()).toEqual("quick brown fox");
});
哲学
这个库诞生于一种孤立地测试一个应用系统的哲学,与在其他系统的活性背景下测试相反. 换句话说:一个应用程序的"单位测试"单个系统相对于其收集的"整合测试".
自动测试应用程序的常规做法是建立一个测试环境,使所有相关的相互依存系统都上网并配置成相互使用.
因此,测试套房在性能上往往会受到影响,因为这种方法不适应规模化,而且测试套房会扩大. 随着一个中度复杂的应用的体面的测试覆盖,将会有大量的跨系统通信,以及对同一种代码路径的多次测试. 这两个都能够显著地减缓整个套房的速度.
当然,整体的,综合的,端到端的测试确实有它的位置,但大多数测试并不需要实际地去执行共同的代码路径和跨系统的反复通信,以使测试有用而有效. 要知道跨系统的通信是 尝试 而不是真实的 执行。 。 。 .
实现这一点的一个办法是传统的依赖性注射。 然而,这往往通过改变函数签名或要求非自然抽象来获得注入到需要的地方来污染源代码的界面. 这个库旨在以透明的方式提供依赖性注射,同时提供必需的"源代码污染"的最小量.
API 密码
有2个主要API用于包装代码,与外部系统相配合. 要使用哪一个取决于被包裹的代码是否会产生值.
对于产生值的代码
如果源代码块产生的值必须在测试中被替换,则使用 extern.validated 或者说 extern.typed。 。 。 .
validated 对 typed
包入源代码块时,有两种模式可供确定如何使用所提供的身份.
使用 validated 使外部块的返回数据由相关方案验证。 这保证了由此产生的数据属于由计划所定义的类型. 如果验证失败, 则 InvalidDataTypeError 会被扔出去 由于标准Schema规格,schema验证可能或可能不返回一个承诺. 为了说明这一点 extern.validated block 总是会返回一个承诺中的结果.
使用 typed 将不会对外部块返回的数据引用任何运行时间验证。 相关身份将仅用于在TypeScript中声明类型,但块返回的实际数据可能根本不是该类型. 如果数据类型已经在区块内被验证,这可以更可取,因为无需为重新验证数据而增加运行时间。 如果您想要手动进行验证, 这一点也可能是理想的 。 块函数的结果将直接作为-is返回.
请注意,可以使用下列方法: extern.typed,但它们仅用于验证TypeScript类型,而非运行时的数据验证.
by
确定外部块所用的方案.
计划必须支持 标准Schema v1,但没有其他要求。 如果您愿意,您可以使用多个不同的计划库.
源代码和测试都应该有完全相同的计划对象,因为没有标准的方法确定代表同一计划结构的不同计划对象之间的平等.
[叹息]
注意一个空的物体计划, 特别是一个 Aync 块功能!
A 承诺本身满足了空界面,而不管它会包到底什么,这会造成类型与由此产生的值相混淆.
见 https://typescript-eslint.io/rules/no-dempty-objective-type 页面存档备份,存于互联网档案馆 (简体中文)
named
命名外部区块只是为了在测试套房中拆分它的模型.
given
外部块通常需要参考自身以外的参数来进行所期望的外部交互. 提供这些参考的一个方法是关闭外部变量:
function comments(postId: number) {
return extern.typed.by(schema).will(
/**
* Makes a closure over the `postId` variable.
*/
() => fetchComments(postId),
);
}
但是,你不妨在测试中断言 提供给外部块的数据。 因此,你可以将数据从外部链中传递到外部块函数中 given数字 :
function comments(postId: number) {
/**
* Parameter for extern block function is provided without the need for a
* closure.
*/
return extern.typed.by(schema).given(postId).will(fetchComments);
}
然后,在测试中可以提供以下数据:
await extern.testing((mock) => {
const spy = mock(schema).with([]);
comments(123);
expect(spy.executions[0]).toMatchObject({ given: 123 });
});
will
定义要按照前面的外部链执行的外部块函数.
它会收到 given 数据作为其唯一的参数.
返回值受相关计划定义的类型及其外链中定义的模式的约束.
混合要求
同步 extern.testing() 身体会同步完成 所以 await 只有在身体本身同步时才需要.
内部 extern.testing(),所有产生值 extern 块 必须 会被嘲笑。 如果使用这样的块时没有注册的模拟器,则会抛出一个出错,即使测试不会以其他方式失败. 这个库的预期是,在测试过程中实际上不会发生外部互动,因为为了性能和可靠性,测试范围应该被隔离. 如果在测试期间确实需要外部互动,则可以通过下列方式在必要时取消要求: passthrough() (见后一节).
而且,默认情况下,任何定义 mock 最终必须在 extern.testing() 块,否则 UnusedMocksError 即使测试不会失败 也会被扔出去 这样做可以避免过分地嘲弄,导致对进行测试实际需要的设置产生混淆. 要禁用此要求, 请通过一个选项对象作为模拟注册的最后一个参数, 以便让该特定模型被使用 : { unused: "allow" }。这可用于断言相应的源代码块确实存在 没有 被处死.
方案要求
在一个 extern 块及其相应的 mock 必须是相同的 JavaScript 对象( 满意) SameValueZero 页:1 因此,应单独界定计划并出口,以便于源代码和测试使用.
令人困惑的嘲弄
如果一个测试将执行多个外部相互作用,这些相互作用在一个单项中使用相同的计划定义 extern.testing() block,该计划定义的模拟注册可能需要分解. 在不产生混淆的情况下,所有数据都将被使用 extern 使用这个计划.
目前,仅 named 支持混淆。 要使用此选项,请定义 extern 块和上 mock数字 :
extern.typed
.by(schema)
.named("abc")
.will(() => 123);
/**
* This mock targets all extern blocks using the schema, regardless of any
* disambiguations that may be assigned to the extern block.
*/
mock(schema).with(321);
/**
* This mock targets all extern blocks using the schema that have been named
* "abc", taking priority over less-specific mocks that would otherwise apply.
*/
mock(schema).named("abc").with(789);
注册一个以上的模拟器, 同样的混淆 相同的计划, 将立即投出一个错误.
跳过模拟
在一些测试中,你也许希望运行原始代码,而不是去嘲笑它,但是不定义一个模拟会扔出一个 UnusedMocksError。 。 。 .
您可以通过明确跳过这个模拟器来实现这一目标:
/** Disables the mocking requirement and runs the original code block. */
mock(schema).skip();
/** Disambiguation is also supported here. */
mock(schema).named("abc").skip();
对于只执行效果的代码
如果源代码块不产生值,则用 extern.effect 允许更简单的整合.
extern.effect.will(() => sendMetric("login.success"));
因为没有返回数据 没有计划 没有 by 这是需要的。 包裹的函数必须返回 void 或者说 Promise<void>。 。 。 .
默认情况下,用 extern.effect 将被跳过 extern.testing(). 与产生价值的区块不同,不需要为它注册一个模拟器;未被模拟的效果根本无济于事.
外部 extern.testing(),所包裹的函数通常运行如 extern 与此事无关.
named
命名效果块,以便在测试中被监视 :
extern.effect
.named("send login metric")
.will(() => sendMetric("login.success"));
在测试中无法观察到未命名的效果块 。 他们总是跳出里面 extern.testing() 没有机会检查他们.
given
就像生产价值的块, given 从外部链向块函数提供数据,而不是通过关闭提供数据,从而在测试中提供数据供断言:
function trackView(postId: number) {
return extern.effect.named("track view").given(postId).will(sendViewMetric);
}
await extern.testing((mock) => {
const spy = mock.effect.named("track view").observe();
trackView(123);
expect(spy.executions[0]).toMatchObject({ given: 123 });
});
given 只有在 named,因为监视所获取的数据 需要识别该块.
will
定义要按照前面的外链执行的效果块函数.
它会收到 given 数据作为其唯一的参数.
返回类型必须是 void 或者说 Promise<void>。 。 。 .
监视效果
在试验期间,可以用两种方式之一观察到命名效应:
/**
* Tracks executions and continues to suppress the original function (the
* default behavior for effects in tests).
*/
const spy = mock.effect.named("track view").observe();
/**
* Tracks executions and allows the original function to run.
*/
const spy = mock.effect.named("track view").passthrough();
每个都返回一个间谍 executions 数组记录每个呼叫到匹配效果块, 并记录任何 given 数据附后。 与产生价值的模拟一样,在交易之前,必须至少进行一次注册效果间谍活动 extern.testing() 块结尾,否则 UnusedMocksError 将会被扔出.
扩展
扩展扩展 单例 接受为块身份,以便 由另一个库的图案构建的块可以产生自己的价值而不是 需要一个模拟器.
import { fabricatorExtension } from "@ghostry/extern-extension-fabricator-v0";
export const extern = initialize({
extensions: [fabricatorExtension({ instance: fabricator })],
});
扩张是 每个实例,而非全球。一个 initialize() 其他地方
同样的项目没有被延期 仍然拒绝这些计划,准确的说
和以前一样 附加到清单中的扩展内容——不需要其他内容
以组合两个.
在一个测试区,一个身份 扩展索赔增加一个 终端 :
await extern.testing((mock) => {
mock(user).produce();
mock(user)
.named("admin")
.produce(({ via }) => via.fabricate({ role: "admin" }));
});
produce() 让扩展名决定值; 回调表将您交给
扩展的自身对象用于该身份—— via ——因此,超音速表示为:
那个图书馆的 词汇,而不是任何外部模型。 两种窗体缓存
百分比 (identity, name),所以在一次测试中读出两次块
调回一次.
写入扩展名
一个 Extension 属于两种变体之一,因下列原因受到歧视: kind。 。 。 .
A 类 生产商 个人身份,必须为其服务:
import type { Extension, TypeLambda } from "@ghostry/extern";
interface MyLambda extends TypeLambda {
readonly Out: MySchema<this["In"]>;
}
const myExtension = (): Extension<MyLambda> => ({
kind: "producer",
name: "my-library",
supports: (identity) => isMySchema(identity),
*frame() {
yield { produce: (identity, named) => buildFrom(identity, named) };
},
});
一个 观察员 没有权利要求,而且每个测试区块只想要一个范围——a
调试帮助记录 哪些块运行,比如。 它没有羊肉,所以
Identity 和每个街区的行为完全一样
已配置扩展名 :
const recorder = (): Extension => ({
kind: "observer",
name: "recorder",
*frame() {
record("entered");
yield {};
},
});
Extension<SomeLambda> 实值 Extension.Producer<SomeLambda>和一个赤裸的
Extension 实值 Extension.Observer。既不承认另一个:生产者
无 supports,一个 unmocked 或会议闭幕的制作人
没有 produce 属于所有类型级编译错误,而不是运行时出乎意料.
frame 每运行一次 extern.testing() 块,用于每个扩展名。 每个
扩展框会附加下一个框架, 所以每个框架在块开始时都会打开
运行.
框架的形状
帧是一个生成器 一个 暂停点。 之前的一切
yield 设置,块运行在 yield之后的一切都会
撕毁 :
const profiler = (): Extension => ({
kind: "observer",
name: "profiler",
*frame() {
const started = performance.now();
const outcome = yield {};
report(performance.now() - started, outcome.ok);
},
});
因为设置和拆卸 共享一个功能—— 当你想要的,一个
try a 包括: finally 之后 yield 在每一个路径上运行: 块经过
块失败,或者你自己的设置 扔在路上之前,块曾经跑.
*frame() {
const conn = pool.acquire();
try {
yield { produce: buildFrom(conn) };
} finally {
pool.release(conn);
}
}
outcome 实值 { ok: true } 或者说 { ok: false, error }因此,撕裂可以显示
从一个失败的街区。 A 类 catch 环绕 yield 永远不要开火 :
extern以结果恢复框架,而不是扔进去,所以
扩展显示失败,但无法拦截或替换。 使用
try编号 :finally没有 try编号 :catch。 。 。 .
async function* 并促成一个承诺——唯一的诚实
以同步撕裂的同步体报告完成的方法.
A 类 同步 发电机同步恢复,因此不能等待
拆解;必须等待的拆解需求 async function*。 。 。 .
里面有东西
当块必须运行时 内部 扩展所打开的东西—— a
AsyncLocalStorage 范围, 图书馆本身 wrap一个集合连接
召回——产生a 包装 而不是一个会议。 它收到一个 body 这个
必须打一次电话,把会议提前,而且会议必须具有何种价值
返回时不变 :
*frame() {
yield (body) => library.wrap(
options,
(scoped) => body({ produce: from(scoped) }),
);
}
目标就是这个 produce 没有可变变量
之间。 Extern在自己的包装箱里解决了你的撕裂问题,所以你有一个范围
打开后仍然直播 yield。 。 。 .
返回块值 不变 永远 extern.testing()
同步为同步试验体. 一个等待着促进每个人的包装
以示承诺.
跨分机拆分
订购不需要协调. 每个框架都包含下一个,所以内在 撕毁在到达外层时已经解决。 减员 解风最先,一个外框等待一个内相同步.
抛出一滴泪也阻止不了兄弟们 每一次失败都被收集出来
报告一次 CleanupFailedError 带着他们 它被扔在当
块本身通过, 仅仅在块失败时登录, 所以失败
值得阅读 永远不会被撕裂的过失所取代.
三个错误被拒绝 而不是被抛在外边作为套房通过
悄悄地跳过撕裂: a frame 返回一个以外的东西
发电机(ExtensionFrameResultError页:1 yield 既无会议,又无会议
包装 (ExtensionFrameSessionError),还有一秒钟 yield
(单位:千美元)ExtensionFrameYieldError) ——有一个街区,所以有一个暂停
点.
羊肉类型
Identity 被一个类型级函数所拓宽,该函数与 this- 类型
谜题 : Apply 相交混凝土 In 在羊肉上读取 Out 回来.
羊群联盟是免费的
工作时没有组合符.
3个作者规则,每个规则都是根据实际计划类型汇编而确定的:
-
this["In"]必须通过一个命名的通用化名.MySchema<this["In"]>决定;{ produces?: this["In"] }没有. -
Out结构必须狭窄键入您自己的标记 值带有。 像松开的形状{ build: () => this["In"] }接受任意 使用同名方法的物体,默默声称从未有过的身份 属于你的。 转而将图书馆的标志相接. -
重叠的羊肉是没有支持的. 如果两个扩展都匹配一个 身份, TypeScript 通过自己的推论- candidate 选择生成的类型 选择, 不论您列出的顺序, 因此没有运行时间 可以发出通知,以同意所发出的呼叫者的类型。 扩展 计数比对而不是立即取出第一个,然后掷出
AmbiguousIdentityError当多个匹配时,命名扩展名.
提供 produce(({ via }) => ...)
回调格式只在您 lambda 扩展时才会出现 HandleLambda页:1
第二,独立配对绘制具体身份图,说明其召回的内容
接收 :
interface MyLambda extends TypeLambda, HandleLambda {
readonly Out: MySchema<this["In"]>;
readonly Handle: MyBuilderFor<this["Of"]>;
}
它是一个单独的接口,而不是两个多的插槽 TypeLambda (单位:千美元)
具体原因: 无论您是否重新声明, 界面成员都会被继承
它,所以一个 Handle 每只羊肉,包括无柄的
——和 MyBuilder | unknown 实值 unknown,将会崩溃 via 改为
unknown 只要一个观察员式的扩展是
配置与您的相邻 .
只有您的扩展可以构建一个手柄, 所以外部路径呼叫者的
更别说自己了. produce 收为第三
参数 :
produce: (identity, named, using) => {
const built = buildFrom(identity, named);
return using === undefined ? built.value() : using(built);
},
没有手柄的扩展名会忽略 using; 离开 Handle 未申报
离开时从身份中撤回回调表 produce()
已经就位了.
驾驭
@ghostry/harness 包裹一个
Jest 兼容测试框架,以便库能为每次测试做出贡献
躯体. @ghostry/extern/harnessing 外部用品:每个试验体
实值 一个测试块, 和它的模拟器到达 测试的背景.
// harness.ts
import { integration as externIntegration } from "@ghostry/extern/harnessing";
import { initialize as initializeHarness } from "@ghostry/harness";
import * as bunTest from "bun:test";
import { extern } from "./extern.ts";
export const { describe, it, expect, beforeAll, beforeEach, framework } =
initializeHarness({
framework: bunTest,
integrations: [externIntegration(extern)],
});
import { it, expect } from "./harness.ts";
import { example, identity } from "./source.ts";
it("substitutes the external interaction", ({ extern: { mock } }) => {
const spy = mock(identity).with("a");
expect(example()).toEqual("a fox");
expect(spy.executions).toHaveLength(1);
});
没有 extern.testing(...) 没有 await 周围的身体: 街区已经
打开,同步测试保持同步.
现在每一次测试都是测试区块
在通过之前先写下这个 在试验区外 外接区会运行
原功能; 在其中之一, 未移动块升起 NotMockedError与
安装的集成设施已经不存在了 所以 每个 测试一下
达到一个包裹的相互作用需要一个模拟器——包括试验,没有人
也就是那些会先失败的测试.
每个街区和每个测试有两个出路:
it("wants the real thing", ({ extern: { mock } }) => {
mock(identity).passthrough();
});
import { framework } from "./harness.ts";
/** The unchanged test module: bodies registered through it are never framed. */
framework.it("is not framed at all", () => {});
第一种方式是将路障置于外部观察之下——它仍然记录着处决——和 运行原始函数。 第二个选择整个测试.
套接字的钩子不是框式的,而是测试的钩子
beforeAll 财务报告和审定财务报表 afterAll 运行在任何测试块之外,所以从
他们履行原来的职能,完全按照他们不会融入的原样
已安装。 在那里,嘲笑者得势 MockingUnavailableError 相当
而不是悄悄地无所事事:
beforeAll(({ extern: { mock } }) => {
mock(identity).with("a"); // MockingUnavailableError
});
这种拒绝是蓄意的。 一个测试块薄荷 自己的间谍, 所以一个嘲笑
定义 beforeAll 即使有人出手,也永远无法进行测试。 A 类
钩子,真正想要一个块 可以打开自己:
beforeAll(async () => {
await extern.testing((mock) => {
mock(identity).with("a");
seed();
});
});
beforeEach 财务报告和审定财务报表 afterEach 不同: 操纵它们 内部 页:1
框,围绕身体, 所以一个模拟定义在一个 beforeEach 测试现场直播
还有一个 afterEach 仍然可以读取它的间谍.
describe("the suite", () => {
beforeEach(({ extern: { mock } }) => {
mock(identity).with("a", { unused: "allow" });
});
});
共享的模拟计算到每个测试的未用模版检查
到达它,这就是什么 { unused: "allow" } 这是为.
需要调和 beforeEach编号 :afterEach 将登记在 describe —— 说
一个顶级的升起 AmbientHookError由于没有套房可以附着
改为:.
与其它融合
整合应用在外, 指数0最外层:
initializeHarness({
framework,
integrations: [fabricatorIntegration(fabricator), externIntegration(extern)],
});
Extern自己的扩展在内部打开它们的范围 testing,所以顺序
集成决定哪个范围包含:
扩展范围相对于其他整合的每个测试范围,以及逆转
他们把每个测试范围 分层在扩展。 都保持每一层,和
既要坚持定型,又要坚持每一次测试——订单只改变层层的方式
窝. 不过,他们不是按同样的配置来编的 所以翻转
命令移动套房中产生的每个值。 选择一个并留下来
示例在此最后记录外部.
在测试中获取编织器数据,分叉 context.fabricator (或
fabricator.context.scope()(没有) fabricator 本身——叉子
集成实例在每次测试中绘制相同的数据。 编织者
扩展的 README 工作了这个案例.
在 sync 范围
scope: "sync" 一次允许一个测试区块。 因为现在每个测试都是
block, 这成为关于测试的规则: 并行的测试机构
IllegalConcurrencyTestingError,明确 extern.testing(...)
写在被陷害的身体里 一个可以调用的现有套房 extern.testing
自己将立即满足这个要求——默认情况下 async 范围相同
筑巢是允许的 但内层的阴影 而不是合并,所以
装入测试的模拟 里面是看不见的.