@uiwwsw/next-test-mode 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +70 -0
- package/LICENSE +21 -0
- package/README.md +170 -0
- package/bin/test-mode.mjs +164 -0
- package/dist/browser.d.ts +7 -0
- package/dist/browser.d.ts.map +1 -0
- package/dist/browser.js +455 -0
- package/dist/browser.js.map +1 -0
- package/dist/client.d.ts +14 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +92 -0
- package/dist/client.js.map +1 -0
- package/dist/core.d.ts +160 -0
- package/dist/core.d.ts.map +1 -0
- package/dist/core.js +741 -0
- package/dist/core.js.map +1 -0
- package/dist/fetch.d.ts +16 -0
- package/dist/fetch.d.ts.map +1 -0
- package/dist/fetch.js +212 -0
- package/dist/fetch.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -0
- package/dist/internal/draft-handler.d.ts +30 -0
- package/dist/internal/draft-handler.d.ts.map +1 -0
- package/dist/internal/draft-handler.js +80 -0
- package/dist/internal/draft-handler.js.map +1 -0
- package/dist/internal/lifecycle.d.ts +7 -0
- package/dist/internal/lifecycle.d.ts.map +1 -0
- package/dist/internal/lifecycle.js +65 -0
- package/dist/internal/lifecycle.js.map +1 -0
- package/dist/internal/next-request.d.ts +11 -0
- package/dist/internal/next-request.d.ts.map +1 -0
- package/dist/internal/next-request.js +22 -0
- package/dist/internal/next-request.js.map +1 -0
- package/dist/internal/overrides.d.ts +25 -0
- package/dist/internal/overrides.d.ts.map +1 -0
- package/dist/internal/overrides.js +111 -0
- package/dist/internal/overrides.js.map +1 -0
- package/dist/internal/paths.d.ts +3 -0
- package/dist/internal/paths.d.ts.map +1 -0
- package/dist/internal/paths.js +22 -0
- package/dist/internal/paths.js.map +1 -0
- package/dist/internal/server-context.d.ts +4 -0
- package/dist/internal/server-context.d.ts.map +1 -0
- package/dist/internal/server-context.js +6 -0
- package/dist/internal/server-context.js.map +1 -0
- package/dist/internal/ssr-state.d.ts +8 -0
- package/dist/internal/ssr-state.d.ts.map +1 -0
- package/dist/internal/ssr-state.js +48 -0
- package/dist/internal/ssr-state.js.map +1 -0
- package/dist/internal/storage.d.ts +6 -0
- package/dist/internal/storage.d.ts.map +1 -0
- package/dist/internal/storage.js +70 -0
- package/dist/internal/storage.js.map +1 -0
- package/dist/internal/symbols.d.ts +3 -0
- package/dist/internal/symbols.d.ts.map +1 -0
- package/dist/internal/symbols.js +3 -0
- package/dist/internal/symbols.js.map +1 -0
- package/dist/next.d.ts +9 -0
- package/dist/next.d.ts.map +1 -0
- package/dist/next.js +32 -0
- package/dist/next.js.map +1 -0
- package/dist/node.d.ts +27 -0
- package/dist/node.d.ts.map +1 -0
- package/dist/node.js +144 -0
- package/dist/node.js.map +1 -0
- package/dist/server.d.ts +20 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +36 -0
- package/dist/server.js.map +1 -0
- package/dist/setup.d.ts +14 -0
- package/dist/setup.d.ts.map +1 -0
- package/dist/setup.js +66 -0
- package/dist/setup.js.map +1 -0
- package/dist/types.d.ts +179 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/docs/architecture.md +116 -0
- package/docs/guide.md +171 -0
- package/docs/migration.md +26 -0
- package/docs/releasing.md +41 -0
- package/docs/server-rendering.md +136 -0
- package/docs/story-test-design.md +252 -0
- package/package.json +136 -0
- package/src/browser.ts +593 -0
- package/src/client.ts +114 -0
- package/src/core.ts +1161 -0
- package/src/fetch.ts +271 -0
- package/src/index.ts +5 -0
- package/src/internal/draft-handler.ts +113 -0
- package/src/internal/lifecycle.ts +81 -0
- package/src/internal/next-request.ts +31 -0
- package/src/internal/overrides.ts +141 -0
- package/src/internal/paths.ts +27 -0
- package/src/internal/server-context.ts +6 -0
- package/src/internal/ssr-state.ts +48 -0
- package/src/internal/storage.ts +75 -0
- package/src/internal/symbols.ts +2 -0
- package/src/next.ts +49 -0
- package/src/node.ts +213 -0
- package/src/server.ts +52 -0
- package/src/setup.ts +69 -0
- package/src/types.ts +240 -0
- package/templates/test-mode/README.md +30 -0
- package/templates/test-mode/config.ts +25 -0
- package/templates/test-mode/features/auth.ts +23 -0
- package/templates/test-mode/index.ts +11 -0
- package/templates/test-mode/install.ts +13 -0
- package/templates/test-mode/stories/auth.stories.ts +10 -0
package/dist/server.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { createTestMode } from "./core.js";
|
|
2
|
+
import { createMockFetch } from "./fetch.js";
|
|
3
|
+
import { readSSRState, ssrCookieKey } from "./internal/ssr-state.js";
|
|
4
|
+
/**
|
|
5
|
+
* Create once per incoming SSR/loader request, never at module scope.
|
|
6
|
+
* Only registered feature selections cross from the browser cookie. Counters,
|
|
7
|
+
* selections and server-side overrides belong to this new runtime instance.
|
|
8
|
+
* Does not install a global fetch or forward incoming cookies to an upstream API.
|
|
9
|
+
*/
|
|
10
|
+
export const createServerTestMode = ({ cookieHeader, originalFetch = globalThis.fetch.bind(globalThis), ssr = false, ...options }) => {
|
|
11
|
+
if (typeof window !== "undefined") {
|
|
12
|
+
throw new TypeError("createServerTestMode must run on the server, once per incoming request. Use createTestMode in the browser.");
|
|
13
|
+
}
|
|
14
|
+
const runtime = createTestMode(options);
|
|
15
|
+
// An absent incoming cookie must not fall back to any other selection source.
|
|
16
|
+
runtime.set(runtime.active(cookieHeader ?? ""));
|
|
17
|
+
if (ssr && runtime.isAvailable()) {
|
|
18
|
+
const state = readSSRState(cookieHeader ?? "", ssrCookieKey(runtime.cookieKey));
|
|
19
|
+
if (state) {
|
|
20
|
+
runtime.set(state.entries);
|
|
21
|
+
for (const item of state.overrides) {
|
|
22
|
+
if (item.mode === "mock")
|
|
23
|
+
runtime.setMock(item.path, item.data, item);
|
|
24
|
+
else
|
|
25
|
+
runtime.setPatch(item.path, item.data, item);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return {
|
|
30
|
+
runtime,
|
|
31
|
+
// Selection is already captured above. An upstream authentication Cookie
|
|
32
|
+
// header must neither change that selection nor suppress local overrides.
|
|
33
|
+
fetch: createMockFetch(runtime, { originalFetch, cookieHeader: false }),
|
|
34
|
+
};
|
|
35
|
+
};
|
|
36
|
+
//# sourceMappingURL=server.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server.js","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE7C,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AAYrE;;;;;GAKG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,EACnC,YAAY,EACZ,aAAa,GAAG,UAAU,CAAC,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,EACjD,GAAG,GAAG,KAAK,EACX,GAAG,OAAO,EACY,EAAE,EAAE;IAC1B,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE,CAAC;QAClC,MAAM,IAAI,SAAS,CACjB,4GAA4G,CAC7G,CAAC;IACJ,CAAC;IACD,MAAM,OAAO,GAAG,cAAc,CAAC,OAAO,CAAC,CAAC;IACxC,8EAA8E;IAC9E,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,YAAY,IAAI,EAAE,CAAC,CAAC,CAAC;IAChD,IAAI,GAAG,IAAI,OAAO,CAAC,WAAW,EAAE,EAAE,CAAC;QACjC,MAAM,KAAK,GAAG,YAAY,CAAC,YAAY,IAAI,EAAE,EAAE,YAAY,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC;QAChF,IAAI,KAAK,EAAE,CAAC;YACV,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YAC3B,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,SAAS,EAAE,CAAC;gBACnC,IAAI,IAAI,CAAC,IAAI,KAAK,MAAM;oBAAE,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;;oBACjE,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,IAA+B,EAAE,IAAI,CAAC,CAAC;YAC/E,CAAC;QACH,CAAC;IACH,CAAC;IACD,OAAO;QACL,OAAO;QACP,yEAAyE;QACzE,0EAA0E;QAC1E,KAAK,EAAE,eAAe,CAAC,OAAO,EAAE,EAAE,aAAa,EAAE,YAAY,EAAE,KAAK,EAAE,CAAC;KACxE,CAAC;AACJ,CAAC,CAAC"}
|
package/dist/setup.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { TestModeOptions, TestModeOverlayOptions } from "./types.js";
|
|
2
|
+
export type SetupTestModeOptions = TestModeOptions & Readonly<{
|
|
3
|
+
/** Opt in to sharing JSON with the server and restoring it after navigation. */
|
|
4
|
+
ssr?: boolean;
|
|
5
|
+
/** SSR defaults to reloading the page after a change. Override for router refresh/refetch. */
|
|
6
|
+
refresh?: () => void;
|
|
7
|
+
overlay?: TestModeOverlayOptions;
|
|
8
|
+
}>;
|
|
9
|
+
/** Install once in the browser entry. Existing fetch calls and Console commands stay the same. */
|
|
10
|
+
export declare const setupTestMode: ({ ssr, refresh, overlay, beforeChange, ...options }?: SetupTestModeOptions) => {
|
|
11
|
+
runtime: import("./core.js").TestMode;
|
|
12
|
+
stop: () => void;
|
|
13
|
+
};
|
|
14
|
+
//# sourceMappingURL=setup.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"setup.d.ts","sourceRoot":"","sources":["../src/setup.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,eAAe,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AAE1E,MAAM,MAAM,oBAAoB,GAAG,eAAe,GAAG,QAAQ,CAAC;IAC5D,gFAAgF;IAChF,GAAG,CAAC,EAAE,OAAO,CAAC;IACd,8FAA8F;IAC9F,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,sBAAsB,CAAC;CAClC,CAAC,CAAC;AAEH,kGAAkG;AAClG,eAAO,MAAM,aAAa,GAAI,sDAM3B,oBAAyB;;;CA8C3B,CAAC"}
|
package/dist/setup.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { createTestMode } from "./core.js";
|
|
2
|
+
import { installMockFetch } from "./fetch.js";
|
|
3
|
+
import { installTestModeOverlay } from "./browser.js";
|
|
4
|
+
import { readSSRState, ssrCookieKey, writeSSRState } from "./internal/ssr-state.js";
|
|
5
|
+
import { createCleanup } from "./internal/lifecycle.js";
|
|
6
|
+
/** Install once in the browser entry. Existing fetch calls and Console commands stay the same. */
|
|
7
|
+
export const setupTestMode = ({ ssr = false, refresh, overlay, beforeChange, ...options } = {}) => {
|
|
8
|
+
let syncing = false;
|
|
9
|
+
let stopped = false;
|
|
10
|
+
let cookieKey = "";
|
|
11
|
+
const runtime = createTestMode({
|
|
12
|
+
...options,
|
|
13
|
+
beforeChange: state => {
|
|
14
|
+
beforeChange?.(state);
|
|
15
|
+
if (syncing)
|
|
16
|
+
writeSSRState(cookieKey, state);
|
|
17
|
+
},
|
|
18
|
+
});
|
|
19
|
+
const cleanups = [];
|
|
20
|
+
let timer;
|
|
21
|
+
const stop = () => {
|
|
22
|
+
if (stopped)
|
|
23
|
+
return;
|
|
24
|
+
stopped = true;
|
|
25
|
+
syncing = false;
|
|
26
|
+
clearTimeout(timer);
|
|
27
|
+
createCleanup(cleanups)();
|
|
28
|
+
};
|
|
29
|
+
if (!runtime.isAvailable())
|
|
30
|
+
return { runtime, stop };
|
|
31
|
+
if (typeof window === "undefined")
|
|
32
|
+
throw new TypeError("setupTestMode runs in the browser. Use withTestMode on the server.");
|
|
33
|
+
cookieKey = ssrCookieKey(runtime.cookieKey);
|
|
34
|
+
if (ssr) {
|
|
35
|
+
const state = readSSRState(document.cookie, cookieKey);
|
|
36
|
+
if (state) {
|
|
37
|
+
runtime.set(state.entries);
|
|
38
|
+
for (const item of state.overrides) {
|
|
39
|
+
if (item.mode === "mock")
|
|
40
|
+
runtime.setMock(item.path, item.data, item);
|
|
41
|
+
else
|
|
42
|
+
runtime.setPatch(item.path, item.data, item);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
// Test cookie availability during setup, before installing globals.
|
|
46
|
+
writeSSRState(cookieKey, { entries: runtime.active(), overrides: runtime.overrides() });
|
|
47
|
+
syncing = true;
|
|
48
|
+
}
|
|
49
|
+
try {
|
|
50
|
+
cleanups.push(installMockFetch(runtime));
|
|
51
|
+
cleanups.push(installTestModeOverlay(runtime, { datasetName: false, ...overlay }));
|
|
52
|
+
const update = refresh ?? (ssr ? () => location.reload() : undefined);
|
|
53
|
+
if (update)
|
|
54
|
+
cleanups.push(runtime.subscribe(() => {
|
|
55
|
+
clearTimeout(timer);
|
|
56
|
+
timer = setTimeout(() => { if (!stopped)
|
|
57
|
+
update(); }, 50);
|
|
58
|
+
}));
|
|
59
|
+
}
|
|
60
|
+
catch (error) {
|
|
61
|
+
stop();
|
|
62
|
+
throw error;
|
|
63
|
+
}
|
|
64
|
+
return { runtime, stop };
|
|
65
|
+
};
|
|
66
|
+
//# sourceMappingURL=setup.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"setup.js","sourceRoot":"","sources":["../src/setup.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAC3C,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AACtD,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,aAAa,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,OAAO,KAAK,EAAE,CAAC;QAAC,IAAI,EAAE,CAAC;QAAC,MAAM,KAAK,CAAC;IAAC,CAAC;IACxC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;AAC3B,CAAC,CAAC"}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import type { TestMode } from "./core.js";
|
|
2
|
+
import type { MOCK_RESULT, MOCK_PASS_THROUGH } from "./internal/symbols.js";
|
|
3
|
+
export type TestModeLogger = Partial<Record<"debug" | "error" | "info" | "warning", (message: string, data?: unknown) => void>>;
|
|
4
|
+
export type MockResult = Readonly<{
|
|
5
|
+
data: unknown;
|
|
6
|
+
/** Explicit JSON encoding, including string payloads. Otherwise BodyInit values stay raw. */
|
|
7
|
+
bodyFormat?: "json";
|
|
8
|
+
headers?: HeadersInit;
|
|
9
|
+
status: number;
|
|
10
|
+
statusText: string;
|
|
11
|
+
}>;
|
|
12
|
+
export type MockHttpResult = MockResult & Readonly<{
|
|
13
|
+
[MOCK_RESULT]: true;
|
|
14
|
+
}>;
|
|
15
|
+
export type MockPassThrough = Readonly<{
|
|
16
|
+
[MOCK_PASS_THROUGH]: true;
|
|
17
|
+
}>;
|
|
18
|
+
export type MockContext<TRequest = unknown> = Readonly<{
|
|
19
|
+
activeKey: string;
|
|
20
|
+
body: TRequest | undefined;
|
|
21
|
+
headers: unknown;
|
|
22
|
+
method: string;
|
|
23
|
+
params: unknown;
|
|
24
|
+
path: string;
|
|
25
|
+
request: TRequest | undefined;
|
|
26
|
+
requestCount: number;
|
|
27
|
+
url: string;
|
|
28
|
+
}>;
|
|
29
|
+
export type MockHandler<TRequest = unknown, TResponse = unknown> = (context: MockContext<TRequest>) => MockHttpResult | MockPassThrough | Promise<TResponse | MockHttpResult | MockPassThrough> | TResponse;
|
|
30
|
+
export type PatchHandler<TRequest = unknown, TResponse = unknown> = (response: TResponse, context: MockContext<TRequest>) => Promise<TResponse> | TResponse;
|
|
31
|
+
export type RouteMatcher = RegExp | string | ((context: Pick<MockContext, "headers" | "method" | "params" | "path" | "url">) => boolean);
|
|
32
|
+
export type MockDefinition<TRequest = unknown, TResponse = unknown> = Readonly<{
|
|
33
|
+
caseKey?: string;
|
|
34
|
+
description?: string;
|
|
35
|
+
handler: MockHandler<TRequest, TResponse>;
|
|
36
|
+
match?: RouteMatcher;
|
|
37
|
+
method?: readonly string[] | string;
|
|
38
|
+
pages?: readonly string[];
|
|
39
|
+
path: string;
|
|
40
|
+
}>;
|
|
41
|
+
export type PatchDefinition<TRequest = unknown, TResponse = unknown> = Readonly<{
|
|
42
|
+
caseKey?: string;
|
|
43
|
+
description?: string;
|
|
44
|
+
handler: PatchHandler<TRequest, TResponse>;
|
|
45
|
+
match?: RouteMatcher;
|
|
46
|
+
method?: readonly string[] | string;
|
|
47
|
+
pages?: readonly string[];
|
|
48
|
+
path: string;
|
|
49
|
+
}>;
|
|
50
|
+
export type RegisteredMockDefinition = MockDefinition<any, any>;
|
|
51
|
+
export type RegisteredPatchDefinition = PatchDefinition<any, any>;
|
|
52
|
+
export type TestModeRequest = Readonly<{
|
|
53
|
+
body?: unknown | undefined;
|
|
54
|
+
cookieHeader?: string | null | undefined;
|
|
55
|
+
headers?: unknown | undefined;
|
|
56
|
+
method: string;
|
|
57
|
+
params?: unknown | undefined;
|
|
58
|
+
path: string;
|
|
59
|
+
url?: string | undefined;
|
|
60
|
+
}>;
|
|
61
|
+
export type TestModePatchRequest = TestModeRequest & Readonly<{
|
|
62
|
+
data: unknown;
|
|
63
|
+
}>;
|
|
64
|
+
export type FeatureCatalogItem = Readonly<{
|
|
65
|
+
active: boolean;
|
|
66
|
+
caseKey?: string;
|
|
67
|
+
description: string;
|
|
68
|
+
key: string;
|
|
69
|
+
mode: "extension" | "mock" | "patch";
|
|
70
|
+
pages: readonly string[];
|
|
71
|
+
path: string;
|
|
72
|
+
}>;
|
|
73
|
+
export type CatalogItem = FeatureCatalogItem;
|
|
74
|
+
export type StoryDefinition = Readonly<{
|
|
75
|
+
description: string;
|
|
76
|
+
entries: readonly string[];
|
|
77
|
+
key: string;
|
|
78
|
+
pages: readonly string[];
|
|
79
|
+
title: string;
|
|
80
|
+
}>;
|
|
81
|
+
export type StoryListOptions = Readonly<{
|
|
82
|
+
active?: boolean;
|
|
83
|
+
page?: string;
|
|
84
|
+
query?: string;
|
|
85
|
+
storyKey?: string;
|
|
86
|
+
}>;
|
|
87
|
+
export type StoryListInput = StoryListOptions | string;
|
|
88
|
+
export type StoryCatalogItem = StoryDefinition & Readonly<{
|
|
89
|
+
active: boolean;
|
|
90
|
+
activeEntries: readonly string[];
|
|
91
|
+
unavailableEntries: readonly string[];
|
|
92
|
+
}>;
|
|
93
|
+
export type TestModeSearchOptions = Readonly<{
|
|
94
|
+
active?: boolean;
|
|
95
|
+
page?: string;
|
|
96
|
+
query?: string;
|
|
97
|
+
}>;
|
|
98
|
+
export type TestModeSearchInput = TestModeSearchOptions | string;
|
|
99
|
+
export type TestModeSearchResult = Readonly<{
|
|
100
|
+
features: readonly FeatureCatalogItem[];
|
|
101
|
+
stories: readonly StoryCatalogItem[];
|
|
102
|
+
}>;
|
|
103
|
+
export type TestModeExtensionContext = Readonly<{
|
|
104
|
+
refresh: () => void;
|
|
105
|
+
testMode: TestMode;
|
|
106
|
+
}>;
|
|
107
|
+
export type TestModeExtension = Readonly<{
|
|
108
|
+
aliases?: readonly string[];
|
|
109
|
+
disable: () => void;
|
|
110
|
+
enable: () => void;
|
|
111
|
+
install?: (context: TestModeExtensionContext) => (() => void) | void;
|
|
112
|
+
isActive: () => boolean;
|
|
113
|
+
key: string;
|
|
114
|
+
label: string;
|
|
115
|
+
subscribe?: (listener: () => void) => () => void;
|
|
116
|
+
toggle?: () => void;
|
|
117
|
+
}>;
|
|
118
|
+
export type ToggleExtensionOptions = Readonly<{
|
|
119
|
+
aliases?: readonly string[];
|
|
120
|
+
key: string;
|
|
121
|
+
label: string;
|
|
122
|
+
onDisable?: () => void;
|
|
123
|
+
onEnable?: () => void;
|
|
124
|
+
setup?: (context: TestModeExtensionContext) => (() => void) | void;
|
|
125
|
+
storageKey?: string;
|
|
126
|
+
}>;
|
|
127
|
+
export type TestModeOptions = Readonly<{
|
|
128
|
+
/** Validate or synchronize a detached state snapshot before a local change commits. Throw to reject it. */
|
|
129
|
+
beforeChange?: (state: TestModeState) => void;
|
|
130
|
+
cookieKey?: string;
|
|
131
|
+
definitions?: readonly RegisteredMockDefinition[];
|
|
132
|
+
enabled?: boolean | (() => boolean);
|
|
133
|
+
eventName?: string;
|
|
134
|
+
logger?: false | TestModeLogger;
|
|
135
|
+
patchDefinitions?: readonly RegisteredPatchDefinition[];
|
|
136
|
+
stories?: readonly StoryDefinition[];
|
|
137
|
+
storageKey?: string;
|
|
138
|
+
}>;
|
|
139
|
+
export type TestModeOverlayOptions = Readonly<{
|
|
140
|
+
/** Set false when installing before React hydration to avoid changing app-owned attributes. */
|
|
141
|
+
datasetName?: string | false;
|
|
142
|
+
document?: Document;
|
|
143
|
+
extensions?: readonly TestModeExtension[];
|
|
144
|
+
globalName?: string;
|
|
145
|
+
installConsole?: boolean;
|
|
146
|
+
namespace?: string;
|
|
147
|
+
watermarkText?: string;
|
|
148
|
+
zIndex?: number;
|
|
149
|
+
}>;
|
|
150
|
+
export type TestModeConsoleOptions = Readonly<{
|
|
151
|
+
extensions?: readonly TestModeExtension[];
|
|
152
|
+
globalName?: string;
|
|
153
|
+
installExtensions?: boolean;
|
|
154
|
+
namespace?: string;
|
|
155
|
+
}>;
|
|
156
|
+
export type TestModeConsoleHelp = Readonly<{
|
|
157
|
+
commands: Readonly<Record<string, string>>;
|
|
158
|
+
examples: readonly string[];
|
|
159
|
+
summary: string;
|
|
160
|
+
}>;
|
|
161
|
+
/** One in-memory, exact-path response experiment. Default method: GET. */
|
|
162
|
+
export type ResponseOverrideOptions = Readonly<{
|
|
163
|
+
method?: string;
|
|
164
|
+
status?: number;
|
|
165
|
+
statusText?: string;
|
|
166
|
+
}>;
|
|
167
|
+
export type ResponseOverride = Readonly<{
|
|
168
|
+
path: string;
|
|
169
|
+
method: string;
|
|
170
|
+
mode: "mock" | "patch";
|
|
171
|
+
data: unknown;
|
|
172
|
+
status?: number;
|
|
173
|
+
statusText?: string;
|
|
174
|
+
}>;
|
|
175
|
+
export type TestModeState = Readonly<{
|
|
176
|
+
entries: readonly string[];
|
|
177
|
+
overrides: readonly ResponseOverride[];
|
|
178
|
+
}>;
|
|
179
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,KAAK,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAE5E,MAAM,MAAM,cAAc,GAAG,OAAO,CAClC,MAAM,CACJ,OAAO,GAAG,OAAO,GAAG,MAAM,GAAG,SAAS,EACtC,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,OAAO,KAAK,IAAI,CAC1C,CACF,CAAC;AAEF,MAAM,MAAM,UAAU,GAAG,QAAQ,CAAC;IAChC,IAAI,EAAE,OAAO,CAAC;IACd,6FAA6F;IAC7F,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,OAAO,CAAC,EAAE,WAAW,CAAC;IACtB,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;CACpB,CAAC,CAAC;AAEH,MAAM,MAAM,cAAc,GAAG,UAAU,GACrC,QAAQ,CAAC;IACP,CAAC,WAAW,CAAC,EAAE,IAAI,CAAC;CACrB,CAAC,CAAC;AAEL,MAAM,MAAM,eAAe,GAAG,QAAQ,CAAC;IACrC,CAAC,iBAAiB,CAAC,EAAE,IAAI,CAAC;CAC3B,CAAC,CAAC;AAEH,MAAM,MAAM,WAAW,CAAC,QAAQ,GAAG,OAAO,IAAI,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AAS,MAAM,EAAE,CAAC;IAC5B,OAAO,EAAE,MAAM,CAAC;CACjB,CAAC,CAAC;AAEH,0EAA0E;AAC1E,MAAM,MAAM,uBAAuB,GAAG,QAAQ,CAAC;IAC7C,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB,CAAC,CAAC;AAEH,MAAM,MAAM,gBAAgB,GAAG,QAAQ,CAAC;IACtC,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC;IACvB,IAAI,EAAE,OAAO,CAAC;IACd,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB,CAAC,CAAC;AAEH,MAAM,MAAM,aAAa,GAAG,QAAQ,CAAC;IACnC,OAAO,EAAE,SAAS,MAAM,EAAE,CAAC;IAC3B,SAAS,EAAE,SAAS,gBAAgB,EAAE,CAAC;CACxC,CAAC,CAAC"}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
# Next Test Mode: architecture and guarantees
|
|
2
|
+
|
|
3
|
+
## Purpose
|
|
4
|
+
|
|
5
|
+
`@uiwwsw/next-test-mode` lets a running application reproduce API-driven UI states by overriding responses at an explicitly connected data boundary. Browser console commands replace or patch browser fetch responses; reusable definitions and stories capture shared scenarios. A visible overlay indicates active test mode on relevant pages. The Next.js adapter uses Draft Mode to preview CSR, SSR, ISR and SSG from the same Console commands.
|
|
6
|
+
|
|
7
|
+
A scenario is a configuration, not an automated test. The library does not make assertions, decide pass/fail, run a browser, host an API, seed a database, or reset application caches. Browser setup can connect an application refetch callback. SSR synchronization defaults to an automatic page reload after changes. Test assertions remain external.
|
|
8
|
+
|
|
9
|
+
## Temporary response values
|
|
10
|
+
|
|
11
|
+
The console exposes `mock`, `patch`, `overrides`, and `reset` for immediate experiments, in memory by default. Core owns these through `setMock`, `setPatch`, `overrides`, and `resetOverrides`. The override registry is separate from the shared feature/story catalog and persistence. It matches the exact normalized pathname and one HTTP method (GET by default), with no API-prefix aliases or patterns. The most recent value for a path/method replaces its predecessor.
|
|
12
|
+
|
|
13
|
+
An override takes precedence over selected definitions for that request. A patch override bypasses a selected mock so that it can operate on the actual HTTP response; a mock override bypasses selected patches. Removing an override reveals the underlying selected scenario. `clear()` removes both. Explicit cookie-scoped requests ignore in-memory overrides to keep server adapters request-scoped.
|
|
14
|
+
|
|
15
|
+
Override values are validated JSON snapshots, copied at input, inspection, and resolution boundaries. Patches shallow-merge object fields and reject non-object upstream payloads. Changes notify subscribers; setup can refresh the app or automatically reload SSR pages. The application owns cache invalidation outside fetch. The Next client coordinates Draft Mode before automatically reloading the page.
|
|
16
|
+
|
|
17
|
+
## Request lifecycle
|
|
18
|
+
|
|
19
|
+
```mermaid
|
|
20
|
+
flowchart TD
|
|
21
|
+
A[Application fetch] --> B{Runtime enabled and route selected?}
|
|
22
|
+
B -->|No| C[Original fetch and untouched response]
|
|
23
|
+
B -->|Yes| D[Normalize request for matching]
|
|
24
|
+
D --> E{Mock returns a result?}
|
|
25
|
+
E -->|Yes| F[Construct mock Response]
|
|
26
|
+
E -->|No or passThrough| G[Original fetch]
|
|
27
|
+
G --> H{Selected patch and response has a body?}
|
|
28
|
+
H -->|No| I[Return original Response immediately]
|
|
29
|
+
H -->|Yes| J[Read payload and run patch]
|
|
30
|
+
J --> K[Return patched Response with transport metadata]
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
The original request arguments are retained for transport. `mapRequest` only changes the runtime's view of the request. Unmatched streams are not cloned or buffered. A selected patch buffers its response to expose a complete payload; do not select patches for infinite SSE streams. Explicit binary content types yield an ArrayBuffer; JSON/text payloads are parsed as JSON when possible, otherwise passed as text. URL, status, redirect/type metadata and application headers survive a patch, including cloning. Byte length, encoding and digest/ETag headers are discarded because their original values no longer describe the payload.
|
|
34
|
+
|
|
35
|
+
Mock and patch features are alternative behaviors for a matching path/method/case. Ambiguous duplicates are rejected. For overlapping patterns with different keys, active keys are visited in sorted order and the first matching definition wins; avoid overlapping patterns when order would matter. Custom match functions should be pure because the adapter can check a match before reading the body and again before executing a handler.
|
|
36
|
+
|
|
37
|
+
## Modules
|
|
38
|
+
|
|
39
|
+
| Area | Responsibility |
|
|
40
|
+
| --- | --- |
|
|
41
|
+
| `src/core.ts` | Definitions, validation, route/case matching, active state, counters, stories, server integration |
|
|
42
|
+
| `src/browser.ts` | Console API, extensions, page-aware overlay, subscriptions, installation and cleanup |
|
|
43
|
+
| `src/fetch.ts` | Request/Response adaptation, transport preservation, cancellation, fetch installation |
|
|
44
|
+
| `src/server.ts` | Incoming-cookie selection and optional JSON handoff, fresh runtime and fetch per request |
|
|
45
|
+
| `src/setup.ts` | One-call browser setup, JSON cookie synchronization, debounced refresh and cleanup |
|
|
46
|
+
| `src/node.ts` | AsyncLocalStorage request wrapper and framework request-context fetch installation |
|
|
47
|
+
| `src/next.ts` | Next Node instrumentation and Draft Mode control route |
|
|
48
|
+
| `src/client.ts` | Serialized Draft handshake, Console setup and refresh |
|
|
49
|
+
| `src/internal/next-request.ts` | Guarded, read-only Next Draft-provider cookie bridge |
|
|
50
|
+
| `src/internal/draft-handler.ts` | Same-origin controls, optional authorization and preview ownership |
|
|
51
|
+
| `src/internal/ssr-state.ts` | Versioned, validated and size-bounded JSON cookie snapshots |
|
|
52
|
+
| `bin/test-mode.mjs` | Next.js instrumentation scaffolding without modifying existing files |
|
|
53
|
+
| `templates/test-mode` | App-owned example definitions, environment configuration and bootstrap |
|
|
54
|
+
| `tests` | Runtime and release regression tests using Node's test runner |
|
|
55
|
+
| `tests/browser` | Chromium integration of the published ESM build and actual SSR HTML |
|
|
56
|
+
| `tests/next` | Installed tarball + CLI in a real Next.js app, unchanged fetch and cache isolation |
|
|
57
|
+
| `scripts/check-package.mjs` | Tarball contents, independent install, public exports and consumer type validation |
|
|
58
|
+
| `.github/workflows` | Repeatable verification and guarded npm publication |
|
|
59
|
+
|
|
60
|
+
The runtime has no external dependencies and no import-time DOM or fetch mutation. The root ESM entry remains compatible; `./core`, `./fetch`, `./browser`, `./setup`, `./server`, `./node`, `./next` and `./client` provide independent entry points. Node built-ins and the optional Next peer are only imported through the Node/Next entries. Shared contracts live in `src/types.ts`, with persistence, path normalization and lifecycle helpers in `src/internal/`. Importing core or server does not load browser rendering or console implementations. Sources are shipped with source maps and declaration maps for debugging.
|
|
61
|
+
|
|
62
|
+
## State and environment
|
|
63
|
+
|
|
64
|
+
Activation defaults to `NODE_ENV=development` or `NODE_ENV=test`. Browsers without `process` must explicitly supply an `enabled` condition. Storage entries cannot enable a disabled runtime. An app can supply a function if availability needs to be evaluated at request time.
|
|
65
|
+
|
|
66
|
+
The browser prefers localStorage and uses cookies for handoff/fallback. Each runtime also maintains an in-memory fallback for denied persistence or quota failure. Browser subscribers receive one notification per local change; instances sharing the configured event name can refresh from storage. Use distinct storage, cookie and event names for independent runtimes on one origin. Defaults are `test-mode.entries`, `test-mode:change`, and console namespace `__testMode`.
|
|
67
|
+
|
|
68
|
+
Without a browser, an instance owns its active state in memory. For shared SSR/server instances, always pass the incoming cookie header (including the empty string when absent) to `resolve`/`applyPatch`. Request counters belong to the runtime instance and entry, so use separate instances if per-request or per-session sequencing is required. This library does not interpret a test-mode cookie as an authentication credential.
|
|
69
|
+
|
|
70
|
+
## Server rendering boundary
|
|
71
|
+
|
|
72
|
+
`createServerTestMode({ cookieHeader, ...options })` creates a new runtime per incoming request. It captures registered feature selection from that request's cookie (null means no selection) and returns a fetch bound to the instance state. It never installs a global hook, forwards an incoming Cookie header, or stores data across requests. The wrapper uses `cookieHeader: false` so outgoing authentication cookies cannot reselect a scenario or suppress an override authored by server code. Existing fetch options retain their string/null/undefined behavior.
|
|
73
|
+
|
|
74
|
+
The factory rejects calls in a browser before any state mutation. Call it inside the server request handler/loader, not at module scope; do not cache its mutable result across requests. Definitions may be shared, but state captured by user handlers is outside the runtime's isolation guarantees.
|
|
75
|
+
|
|
76
|
+
`setupTestMode({ ssr: true })` synchronously validates and writes a versioned JSON cookie before committing local state. A detached candidate snapshot keeps failed writes and oversized payloads from partially changing the active runtime. The cookie carries entries and JSON overrides, is bounded to 3,500 encoded ASCII bytes, and restores values after reload. SSR sync is opt-in; default browser overrides remain in memory. The manual server factory also requires `ssr: true`; automatic server installers accept synchronization by default. Cookies are browser-session scoped, shared by tabs, and cannot enable a disabled server runtime. Malformed snapshots are ignored as a whole.
|
|
77
|
+
|
|
78
|
+
`withTestMode(handler)` installs a dispatcher once and uses AsyncLocalStorage for each incoming Node request. Unchanged global fetch calls use that request's runtime; outside the scope they use the original transport. Response completion deactivates the scope. Active test responses receive private/no-store headers. Cleanup supports nested installs and preserves newer third-party hooks.
|
|
79
|
+
|
|
80
|
+
`installServerTestMode({ getRequest })` supports frameworks with their own current-request accessor. A WeakMap keyed by request identity keeps selections and counters local. A fetch accessor follows later framework replacements, while function proxies preserve framework marker properties. AsyncLocalStorage bypasses recursive interception. `setupNextTestMode()` checks public `draftMode()` without opting ordinary requests into dynamic rendering. Active Draft sessions use a guarded read-only bridge into the internal provider cookie jar for request identity and test cookies, including inside cache scopes. This version-sensitive boundary is tested against Next 16.3.5; unsupported provider shapes throw. Startup and generateStaticParams fetches pass through. Override responses sit outside Next's fetch cache: mocked values never enter it, and patches only transform the returned response. Request-context errors that signal dynamic rendering are rethrown; unscoped startup fetches pass through.
|
|
81
|
+
|
|
82
|
+
The new browser setup disables app-owned html/body dataset markers by default to avoid mutating React hydration attributes. The visible overlay still works. Low-level overlay defaults stay compatible; callers may explicitly set `datasetName` or false. Both setup and adapters are explicit installations with cleanup, not import-time hooks.
|
|
83
|
+
|
|
84
|
+
Draft Mode bypasses normal Next page/data caches for a browser session. SSR, SSG, ISR, force-static, generated routes, unstable_cache and Cache Components/use cache are exercised in real production fixtures; the ordinary prerender manifest and anonymous cached output stay intact. Pure static export, Pages Router, Edge, direct DB calls and external caches are outside the automatic adapter. CI verifies raw HTML, second-browser isolation, clear-to-cache behavior, hydration, and a production build with the tool disabled. See [server integration](./server-rendering.md).
|
|
85
|
+
|
|
86
|
+
## Contracts
|
|
87
|
+
|
|
88
|
+
- GET/HEAD use query parameters as `body`/`request`; DELETE and other body-capable methods expose their body. Query params are not route-param extraction.
|
|
89
|
+
- `RequestInit.headers` replaces Request headers. Reading a Request body for mocking does not consume the original input used by the network adapter.
|
|
90
|
+
- `resolve()` returns an HTTP result envelope or null for no match/pass-through. Handler exceptions reject; they are not silently converted to network requests.
|
|
91
|
+
- `applyPatch()` returns `{ data }`, including `{ data: null }`, or null for no match. `patch()` is the older payload-only API with an ambiguous null sentinel.
|
|
92
|
+
- A mock response can be JSON, text or a native BodyInit value. `bodyFormat: "json"` explicitly JSON-encodes strings as well; temporary mocks use this format. HEAD/204/205/304 remain bodyless. Opaque responses and bodyless upstream responses bypass patching.
|
|
93
|
+
- Abort signals reject waiting callers promptly, including while an asynchronous mock is pending. Arbitrary user handler side effects cannot be forcibly cancelled.
|
|
94
|
+
- Selecting a case removes all selected cases that conflict on path and HTTP method. Story registration rejects conflicting cases and missing/duplicate metadata or unknown entries. Failed registration does not partially mutate the existing catalog.
|
|
95
|
+
- Selecting a story replaces active feature entries; adding a story preserves compatible entries. Story removal removes its referenced entries even if another story also references them.
|
|
96
|
+
- `pages` controls discovery and overlay visibility, not whether an API is intercepted. A feature without pages is global; a story must have explicit or inherited pages.
|
|
97
|
+
- Fetch cleanup restores the exact previous function and tolerates nested installs removed in either order. It does not overwrite a newer third-party hook.
|
|
98
|
+
- Overlay cleanup removes the DOM, dataset markers, subscriptions and scheduled navigation refresh. Nested overlay/console installations preserve owned globals, dataset markers and history methods when removed in either order. Setup failures unwind previously acquired resources, and all cleanup runs even if an extension teardown throws.
|
|
99
|
+
|
|
100
|
+
## Compatibility changes before the first registry release
|
|
101
|
+
|
|
102
|
+
The source-only scaffold used Dominos-specific storage/event names and assumed an absent NODE_ENV meant development. The first registry release uses neutral names and explicit development/test activation. Existing scaffold adopters can supply the old keys explicitly to retain saved scenarios. A global browser runtime must now set `enabled` deliberately.
|
|
103
|
+
|
|
104
|
+
## Release contract
|
|
105
|
+
|
|
106
|
+
A release must have an existing `v<package.version>` tag, matching lockfile versions, and a commit included in `origin/main`. Runtime, packaging, browser and actual Next.js checks must all pass before the publish job can run. Stable versions use npm's latest channel; prereleases use next. A GitHub release's prerelease flag must agree with the version. Publish credentials are only exposed to publication and the old-package migration notice step; checkout credentials are not persisted. npm publication is immutable, so changes after a release need a new version.
|
|
107
|
+
|
|
108
|
+
References: [Fetch standard](https://fetch.spec.whatwg.org/), [npm publishing](https://docs.npmjs.com/cli/v11/commands/npm-publish/), [npm trusted publishing](https://docs.npmjs.com/trusted-publishers/).
|
|
109
|
+
|
|
110
|
+
## Draft lifecycle and control isolation
|
|
111
|
+
|
|
112
|
+
The client writes the bounded JSON snapshot first, then sends an authenticated-by-origin POST through the original fetch captured before installation. Requests serialize and reconcile the latest snapshot; acknowledged snapshots suppress duplicate refresh timers. Startup reconciles an expired deployment Draft cookie or an owned session with no remaining overrides. Failures reject `ready`/`sync`, report an error and do not reload; the prior local cookie write may already have succeeded.
|
|
113
|
+
|
|
114
|
+
The control route validates environment, method, Origin/Host, custom header, fetch metadata, JSON and a 1,024-byte body bound. Optional application authorization runs in an AsyncLocalStorage bypass context, so test mocks cannot forge its fetch response. The same bypass covers Draft bookkeeping. An HttpOnly ownership marker allows clear to close sessions opened by this tool while preserving a previously active CMS preview. The application remains responsible for protecting its preview environment and server-rendered routes.
|
|
115
|
+
|
|
116
|
+
Next Draft Mode controls caching; overrides remain outside Next's fetch cache. The private bridge only reads the two configured test cookies, never forwards the incoming authentication header, and never mutates Next internals. Upgrades must pass production integration checks; a matching peer range alone does not certify future Next releases.
|
package/docs/guide.md
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
# 사용 가이드
|
|
2
|
+
|
|
3
|
+
> **Next.js App Router:** 먼저 `npm install @uiwwsw/next-test-mode`와 `npx @uiwwsw/next-test-mode init`을 실행하세요. 생성된 `/client` 연결이 Console·Draft Mode·자동 새로고침을 처리합니다. 아래 범용 설치 예제를 중복 설치하지 마세요. SSR·SSG·ISR 지원 범위는 [Next 연결 가이드](./server-rendering.md), 기존 패키지 이전은 [migration](./migration.md)을 확인하세요.
|
|
4
|
+
|
|
5
|
+
설치와 첫 실행은 [README](https://github.com/uiwwsw/next-test-mode#readme)를 참고하세요.
|
|
6
|
+
|
|
7
|
+
Next Test Mode는 **API 응답을 바꾸는 UI 디버깅 도구**입니다. `setupTestMode()`로 브라우저에 한 번 연결합니다. Next.js는 `npx @uiwwsw/next-test-mode init`, Node는 `withTestMode()`로 서버도 연결하면 직접 입력한 JSON을 SSR에 전달하고 자동 새로고침합니다. [CSR / SSR 지원 범위와 연결 예제](./server-rendering.md).
|
|
8
|
+
|
|
9
|
+
## 직접 응답 값 넣기
|
|
10
|
+
|
|
11
|
+
콘솔의 `test.mock(path, data, options?)`는 등록 없이 즉시 응답을 교체하고, `test.patch(path, fields, options?)`는 실제 응답의 필드를 변경합니다.
|
|
12
|
+
|
|
13
|
+
```js
|
|
14
|
+
test.mock('/api/cart', { items: [], total: 0 });
|
|
15
|
+
test.patch('/api/cart', { total: 9.99 });
|
|
16
|
+
test.mock('/api/login', { message: 'Locked' }, { method: 'POST', status: 403 });
|
|
17
|
+
test.overrides(); // [{ path, method, mode, data, ... }]
|
|
18
|
+
test.reset('/api/cart', { method: 'GET' });
|
|
19
|
+
test.reset(); // 모든 임시 값 제거. 선택된 feature/story는 유지
|
|
20
|
+
test.clear(); // 임시 값, feature/story, extension 모두 끄기
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
- 기본 method는 GET이며 대소문자를 정규화합니다. 경로는 `/`로 시작하는 정확한 pathname입니다. query/hash는 제외하고 origin은 구분하지 않습니다. feature의 `/api` 별칭·패턴 매칭은 임시 값에 적용하지 않습니다.
|
|
24
|
+
- 같은 경로·method에 다시 입력하면 이전 임시 값을 교체합니다. 임시 값이 선택된 feature/story보다 우선합니다. Patch는 기존 Mock도 우회하고 실제 HTTP 응답에 적용합니다. `reset()`하면 아래에 있던 feature/story가 다시 적용되므로 완전히 실제 API로 돌아가려면 `clear()`를 사용하세요.
|
|
25
|
+
- Mock은 JSON 객체·배열·문자열·숫자·boolean·null을 지원합니다. HTTP 상태는 200–599이며 HEAD/204/205/304의 본문은 생략합니다. 함수·순환 참조·undefined·NaN 등은 거부합니다. 입력 실패 시 기존 값은 유지합니다.
|
|
26
|
+
- Patch는 객체의 최상위 필드를 덮어씁니다. 중첩 객체나 배열은 통째로 교체합니다. 원래 응답이 객체가 아니면 오류를 내므로 전체 교체가 필요할 때는 Mock을 쓰세요.
|
|
27
|
+
- 입력과 조회 결과는 복사됩니다. 기본값은 runtime 메모리 전용입니다. `setupTestMode({ ssr: true })`는 쿠키에 저장해 같은 브라우저의 서버 요청과 공유하고 새로고침 후 복원합니다. 전체 상태는 인코딩 후 3,500바이트까지이며 초과하면 기존 값을 유지합니다. 수동 core API의 명시적인 `cookieHeader` 선택은 기존대로 동작합니다.
|
|
28
|
+
- `test.isEnabled()`와 오버레이는 임시 값도 반영합니다. `runtime.active()`는 등록된 feature 선택만 반환하며, 임시 값은 `runtime.overrides()`로 확인합니다.
|
|
29
|
+
- `setupTestMode({ refresh })`에 앱의 재요청 함수를 연결할 수 있습니다. SSR 동기화 모드의 기본 refresh는 페이지 새로고침입니다. fetch 밖에 있는 앱 캐시의 무효화는 앱에서 수행합니다.
|
|
30
|
+
|
|
31
|
+
TypeScript나 서버 어댑터에서는 같은 기능을 `runtime.setMock()`, `runtime.setPatch()`, `runtime.overrides()`, `runtime.resetOverrides()`로 사용합니다. `runtime.patch()`는 기존 응답 처리 API이므로 그대로 유지합니다.
|
|
32
|
+
|
|
33
|
+
## Mock, Patch, 요청 데이터
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
import { defineMock, definePatch, httpResult, passThrough } from '@uiwwsw/next-test-mode';
|
|
37
|
+
|
|
38
|
+
// HTTP 오류 응답. 오류를 throw하는 것과 달리 fetch 자체는 resolve됩니다.
|
|
39
|
+
const locked = defineMock('/api/login', () => httpResult({
|
|
40
|
+
data: { message: 'Account locked' },
|
|
41
|
+
status: 403,
|
|
42
|
+
statusText: 'Forbidden',
|
|
43
|
+
}), { caseKey: 'locked', method: 'POST', pages: ['/login'] });
|
|
44
|
+
|
|
45
|
+
// 타입이 있는 요청과 응답을 정의할 수 있습니다.
|
|
46
|
+
const greeting = defineMock<{ name: string }, { greeting: string }>(
|
|
47
|
+
'/api/hello',
|
|
48
|
+
({ body }) => ({ greeting: `Hello ${body?.name ?? 'world'}` }),
|
|
49
|
+
{ method: 'POST' },
|
|
50
|
+
);
|
|
51
|
+
|
|
52
|
+
// 실제 API를 호출한 다음 payload만 변경합니다.
|
|
53
|
+
const outOfStock = definePatch<unknown, { stock: number }>(
|
|
54
|
+
'/api/products/:id',
|
|
55
|
+
(response) => ({ ...response, stock: 0 }),
|
|
56
|
+
{ pages: ['/products'] },
|
|
57
|
+
);
|
|
58
|
+
|
|
59
|
+
// 특정 요청만 mock, 나머지는 실제 API로 전달합니다.
|
|
60
|
+
const search = defineMock('/api/search', ({ params }) =>
|
|
61
|
+
(params as { q?: string }).q === 'empty' ? { results: [] } : passThrough(),
|
|
62
|
+
);
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
mock은 `definitions`, patch는 `patchDefinitions`에 등록해야 합니다. 정의는 등록만으로 활성화되지 않으며 story 또는 feature 선택이 필요합니다.
|
|
66
|
+
|
|
67
|
+
- `body` / `request`: GET·HEAD는 query params, POST·PUT·PATCH·DELETE는 요청 본문입니다.
|
|
68
|
+
- `params`: query string을 객체로 변환한 값입니다. 같은 키가 여러 번 있으면 마지막 값이 남습니다. 경로의 `:id`를 추출하는 기능은 아닙니다.
|
|
69
|
+
- `headers`, `method`, `path`, `url`: 요청을 검사할 수 있습니다. fetch 어댑터의 `headers`는 `Headers`입니다.
|
|
70
|
+
- `requestCount`: 해당 런타임 인스턴스와 feature key의 호출 횟수입니다. 서버의 사용자별 카운터는 아닙니다.
|
|
71
|
+
- 반환값은 JSON으로 직렬화합니다. 문자열, Blob, FormData, URLSearchParams, ArrayBuffer, typed array, ReadableStream은 원래 body 형식으로 처리합니다.
|
|
72
|
+
- HEAD와 204·205·304에는 본문을 넣지 않습니다. 해당 실제 응답은 patch도 건너뜁니다.
|
|
73
|
+
- 취소된 fetch는 reject됩니다. 이미 시작된 사용자 작성 비동기 handler 자체를 강제로 중지하지는 않습니다.
|
|
74
|
+
|
|
75
|
+
## 경로 매칭
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
defineMock('/api/orders/:id', () => ({ id: 1 }));
|
|
79
|
+
defineMock('/api/orders/*', () => []);
|
|
80
|
+
// 정규식은 첫 인자가 아니라 match 옵션으로 전달합니다.
|
|
81
|
+
defineMock('/order-by-id', () => ({ id: 1 }), { match: /^\/api\/orders\/\d+$/ });
|
|
82
|
+
defineMock('/api/orders', () => [], {
|
|
83
|
+
match: ({ url, method }) => new URL(url).origin === 'https://api.example.com' && method === 'GET',
|
|
84
|
+
});
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
기본 매칭은 origin, query, hash를 제외한 pathname 기준이며 `/api/orders`와 `/orders`를 같은 경로로 취급합니다. 여러 API 호스트를 구분해야 하면 `match`에서 URL도 검사하세요. 정규식·함수 matcher도 등록 key를 활성화해야 동작합니다.
|
|
88
|
+
|
|
89
|
+
`mapRequest`는 프록시 경로를 매칭용 경로로 바꿀 때 사용합니다. 실제 네트워크 요청 인자는 변경하지 않습니다.
|
|
90
|
+
|
|
91
|
+
```ts
|
|
92
|
+
installMockFetch(runtime, {
|
|
93
|
+
mapRequest: request => ({
|
|
94
|
+
...request,
|
|
95
|
+
path: request.path.replace(/^\/proxy/, '/api'),
|
|
96
|
+
}),
|
|
97
|
+
});
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
## 콘솔 API와 시나리오 규칙
|
|
101
|
+
|
|
102
|
+
```js
|
|
103
|
+
test.search(); // feature와 story 전체 검색
|
|
104
|
+
test.search({ page: '/cart', query: 'empty', active: true });
|
|
105
|
+
test.feat.list();
|
|
106
|
+
test.feat.add('/api/cart:empty');
|
|
107
|
+
test.feat.remove('/api/cart:empty');
|
|
108
|
+
test.feat.toggle('/api/cart:empty');
|
|
109
|
+
test.feat.set(['/api/cart:empty']);
|
|
110
|
+
test.story.list();
|
|
111
|
+
test.story.add('cart.empty');
|
|
112
|
+
test.story.remove('cart.empty');
|
|
113
|
+
test.story.toggle('cart.empty');
|
|
114
|
+
test.story.set(['cart.empty']);
|
|
115
|
+
test('cart.empty'); // story key이면 선택, 아니면 feature 토글
|
|
116
|
+
test.active();
|
|
117
|
+
test.clear();
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
story는 고유한 `key`, `title`, `description`, 등록된 `entries`가 필요합니다. 화면 경로 `pages`는 feature에서 상속하거나 story에 명시해야 합니다. 같은 경로·HTTP 메서드의 상충하는 case를 한 story에 넣으면 등록 시 오류가 납니다. feature 선택 시에는 나중에 선택한 case가 기존의 상충하는 case를 교체합니다. 동일 entry의 중복 정의는 메서드 범위가 겹치지 않을 때만 허용합니다.
|
|
121
|
+
|
|
122
|
+
선택 상태는 localStorage와 cookie에 보관합니다. 저장소가 차단되거나 용량이 부족하면 인스턴스 메모리를 사용합니다. 기본 키는 `test-mode.entries`, 변경 이벤트는 `test-mode:change`입니다. 여러 앱을 한 origin에서 운영한다면 `storageKey`, `cookieKey`, `eventName`을 각각 지정하세요.
|
|
123
|
+
|
|
124
|
+
## 앱에 적용하기
|
|
125
|
+
|
|
126
|
+
**기존 호출 코드는 그대로 두고, 테스트 데이터와 시나리오는 앱 소유의 폴더에 모으세요.** 브라우저 fetch를 앱 시작 시 한 번 연결하면 호출부마다 테스트 전용 분기를 넣을 필요가 없습니다. 한 번 확인할 값은 콘솔의 `test.mock()` / `test.patch()`로만 사용하고, 반복할 동작만 파일로 남길 수 있습니다.
|
|
127
|
+
|
|
128
|
+
스타터를 복사한 뒤 `config.ts`의 `enabled`를 앱 환경에 맞게 설정하세요. 이 폴더는 패키지 내부가 아니라 여러분의 앱 코드이므로 필요한 데이터와 시나리오를 직접 수정하고 코드 리뷰할 수 있습니다.
|
|
129
|
+
|
|
130
|
+
```bash
|
|
131
|
+
cp -R node_modules/@uiwwsw/next-test-mode/templates/test-mode src/test-mode
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
```text
|
|
135
|
+
src/test-mode/
|
|
136
|
+
config.ts # 환경 조건, 저장소 키, 표시 설정
|
|
137
|
+
index.ts # runtime 생성
|
|
138
|
+
install.ts # 설치 및 cleanup
|
|
139
|
+
features/auth.ts # API 동작
|
|
140
|
+
stories/auth.stories.ts # QA 시나리오
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
React/Next.js의 effect에서는 `return installAppTestMode()`로 정리 함수를 반환하세요. Vite의 HMR에서는 `import.meta.hot?.dispose(cleanup)`을 사용하세요. Vue/일반 앱은 클라이언트 bootstrap에서 한 번 설치하고 앱을 해제할 때 cleanup을 호출합니다.
|
|
144
|
+
|
|
145
|
+
기존 API 모듈은 계속 `fetch('/api/cart')`를 호출합니다. 별도 폴더의 동작을 등록하고 콘솔에서 `test.story('cart.empty')`처럼 선택하면 다음 API 응답부터 바뀝니다. 앱의 재요청 방식은 그대로 사용하거나 `runtime.subscribe()`에 연결하세요. SSR 자동 연결은 서버 시작 지점에 한 번 설치합니다.
|
|
146
|
+
|
|
147
|
+
## 서버 / axios 어댑터
|
|
148
|
+
|
|
149
|
+
Next.js는 `init`, 일반 Node는 `withTestMode(handler)`로 시작 지점에 한 번 연결하면 fetch 호출부를 유지합니다. 필요한 조회만 수동 연결할 때는 요청마다 `createServerTestMode({ cookieHeader, ssr: true, ...options })`를 생성하세요. 반환된 `runtime`과 `fetch`는 그 요청 전용입니다. [서버 렌더링 가이드](./server-rendering.md)에서 공유 시나리오·Next.js·캐시 조건을 확인하세요.
|
|
150
|
+
|
|
151
|
+
서버나 fetch를 사용하지 않는 API 클라이언트는 `runtime.resolve(request)`와 `runtime.applyPatch({ ...request, data })`로 연결할 수 있습니다.
|
|
152
|
+
|
|
153
|
+
```ts
|
|
154
|
+
const request = {
|
|
155
|
+
method: 'GET',
|
|
156
|
+
path: '/api/cart',
|
|
157
|
+
cookieHeader: incomingRequest.headers.get('cookie') ?? '',
|
|
158
|
+
};
|
|
159
|
+
const mock = await runtime.resolve(request);
|
|
160
|
+
if (mock) {
|
|
161
|
+
// 어댑터가 mock.data, status, statusText, headers를 실제 응답으로 변환
|
|
162
|
+
} else {
|
|
163
|
+
const upstreamData = await callUpstream();
|
|
164
|
+
const patched = await runtime.applyPatch({ ...request, data: upstreamData });
|
|
165
|
+
const data = patched === null ? upstreamData : patched.data;
|
|
166
|
+
}
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
서버에서는 모든 요청에 `cookieHeader`를 명시해야 사용자별 선택 상태가 섞이지 않습니다. 활성화 cookie는 인증 수단이 아닙니다. 앱의 환경·접근 조건으로 test mode 사용 범위를 결정하세요. 기존 `patch()`도 유지하지만 `null` payload와 매칭 실패를 구분하려면 `applyPatch()`를 사용하세요.
|
|
170
|
+
|
|
171
|
+
상세 동작과 한계: [설계 및 보장 범위](./architecture.md), [Story 설계](./story-test-design.md).
|