@visiblevc/ember-api-mocks 0.0.0-stage → 0.1.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/LICENSE.md +9 -0
- package/README.md +369 -2
- package/addon-main.cjs +4 -0
- package/declarations/api.d.ts +46 -0
- package/declarations/api.d.ts.map +1 -0
- package/declarations/beacon.d.ts +3 -0
- package/declarations/beacon.d.ts.map +1 -0
- package/declarations/config.d.ts +23 -0
- package/declarations/config.d.ts.map +1 -0
- package/declarations/factories.d.ts +53 -0
- package/declarations/factories.d.ts.map +1 -0
- package/declarations/fetch-waiter.d.ts +7 -0
- package/declarations/fetch-waiter.d.ts.map +1 -0
- package/declarations/formats.d.ts +37 -0
- package/declarations/formats.d.ts.map +1 -0
- package/declarations/index.d.ts +8 -0
- package/declarations/index.d.ts.map +1 -0
- package/declarations/inflection.d.ts +6 -0
- package/declarations/inflection.d.ts.map +1 -0
- package/declarations/network.d.ts +15 -0
- package/declarations/network.d.ts.map +1 -0
- package/declarations/setup.d.ts +6 -0
- package/declarations/setup.d.ts.map +1 -0
- package/declarations/store.d.ts +6 -0
- package/declarations/store.d.ts.map +1 -0
- package/dist/index.js +1290 -0
- package/dist/index.js.map +1 -0
- package/package.json +149 -3
- package/src/api.ts +485 -0
- package/src/beacon.ts +25 -0
- package/src/config.ts +77 -0
- package/src/factories.ts +404 -0
- package/src/fetch-waiter.ts +161 -0
- package/src/formats.ts +231 -0
- package/src/index.ts +31 -0
- package/src/inflection.ts +53 -0
- package/src/network.ts +206 -0
- package/src/setup.ts +30 -0
- package/src/store.ts +214 -0
package/src/formats.ts
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import {
|
|
2
|
+
camelize,
|
|
3
|
+
dasherize,
|
|
4
|
+
pluralize,
|
|
5
|
+
singularize,
|
|
6
|
+
underscore,
|
|
7
|
+
} from './inflection.ts';
|
|
8
|
+
|
|
9
|
+
export type Attrs = Record<string, unknown>;
|
|
10
|
+
export type BuiltRecord = Attrs & { id: unknown };
|
|
11
|
+
export type RelationshipKind = 'belongsTo' | 'hasMany';
|
|
12
|
+
|
|
13
|
+
export interface Relationship {
|
|
14
|
+
type: string;
|
|
15
|
+
kind: RelationshipKind;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface Related {
|
|
19
|
+
type: string;
|
|
20
|
+
record: BuiltRecord;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface DocumentContext {
|
|
24
|
+
seeding: boolean;
|
|
25
|
+
related(record: BuiltRecord): Related[];
|
|
26
|
+
relationships(record: BuiltRecord): Map<string, Relationship>;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface Format {
|
|
30
|
+
readonly updateMethod: 'put' | 'patch';
|
|
31
|
+
readonly separatesRelationships: boolean;
|
|
32
|
+
keyError(key: string): string | undefined;
|
|
33
|
+
relationshipKey(key: string, kind: RelationshipKind): string;
|
|
34
|
+
path(type: string): string;
|
|
35
|
+
document(
|
|
36
|
+
type: string,
|
|
37
|
+
data: BuiltRecord | BuiltRecord[],
|
|
38
|
+
extra: Attrs,
|
|
39
|
+
context: DocumentContext,
|
|
40
|
+
): Attrs;
|
|
41
|
+
idFromBody(type: string, body: unknown): unknown;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
type KeyCase = 'snake' | 'camel' | 'dash';
|
|
45
|
+
|
|
46
|
+
const KEY_RULES: Record<KeyCase, { invalid: RegExp; description: string }> = {
|
|
47
|
+
snake: { invalid: /[A-Z-]/, description: 'snake_case' },
|
|
48
|
+
camel: { invalid: /[_-]/, description: 'camelCase' },
|
|
49
|
+
dash: { invalid: /[A-Z_]/, description: 'dasherized' },
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
function keyError(keys: KeyCase, key: string): string | undefined {
|
|
53
|
+
const rule = KEY_RULES[keys];
|
|
54
|
+
return rule.invalid.test(key)
|
|
55
|
+
? `Overrides use the API's ${rule.description} keys.`
|
|
56
|
+
: undefined;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function collect(records: BuiltRecord[], context: DocumentContext): Related[] {
|
|
60
|
+
const seen = new Set<BuiltRecord>(records);
|
|
61
|
+
const result: Related[] = [];
|
|
62
|
+
const visit = (record: BuiltRecord) => {
|
|
63
|
+
for (const related of context.related(record)) {
|
|
64
|
+
if (!seen.has(related.record)) {
|
|
65
|
+
seen.add(related.record);
|
|
66
|
+
result.push(related);
|
|
67
|
+
visit(related.record);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
records.forEach(visit);
|
|
72
|
+
return result;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function idUnder(body: unknown, key: string): unknown {
|
|
76
|
+
const root =
|
|
77
|
+
body !== null && typeof body === 'object' ? (body as Attrs)[key] : null;
|
|
78
|
+
return root !== null && typeof root === 'object'
|
|
79
|
+
? (root as Attrs).id
|
|
80
|
+
: undefined;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function sideloaded(
|
|
84
|
+
rootKey: (type: string, plural: boolean) => string,
|
|
85
|
+
): Pick<Format, 'document' | 'idFromBody'> {
|
|
86
|
+
return {
|
|
87
|
+
document(type, data, extra, context) {
|
|
88
|
+
const many = Array.isArray(data);
|
|
89
|
+
const records = many ? data : [data];
|
|
90
|
+
const result: Attrs = { [rootKey(type, many)]: many ? [...data] : data };
|
|
91
|
+
for (const { type: relatedType, record } of collect(records, context)) {
|
|
92
|
+
const key = rootKey(relatedType, true);
|
|
93
|
+
((result[key] ??= []) as BuiltRecord[]).push(record);
|
|
94
|
+
}
|
|
95
|
+
return { ...result, ...extra };
|
|
96
|
+
},
|
|
97
|
+
idFromBody: (type, body) => idUnder(body, rootKey(type, false)),
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function activeModel(): Format {
|
|
102
|
+
const rootKey = (type: string, plural: boolean) =>
|
|
103
|
+
plural ? pluralize(underscore(type)) : underscore(type);
|
|
104
|
+
|
|
105
|
+
return {
|
|
106
|
+
updateMethod: 'put',
|
|
107
|
+
separatesRelationships: false,
|
|
108
|
+
keyError: (key) => keyError('snake', key),
|
|
109
|
+
relationshipKey: (key, kind) =>
|
|
110
|
+
kind === 'belongsTo' ? `${key}_id` : `${singularize(key)}_ids`,
|
|
111
|
+
path: (type) => `/${rootKey(type, true)}`,
|
|
112
|
+
...sideloaded(rootKey),
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export interface RestOptions {
|
|
117
|
+
keys?: KeyCase;
|
|
118
|
+
path?: (type: string) => string;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function rest(options: RestOptions = {}): Format {
|
|
122
|
+
const keys = options.keys ?? 'camel';
|
|
123
|
+
const cased = (type: string) =>
|
|
124
|
+
keys === 'snake'
|
|
125
|
+
? underscore(type)
|
|
126
|
+
: keys === 'dash'
|
|
127
|
+
? dasherize(type)
|
|
128
|
+
: camelize(type);
|
|
129
|
+
const rootKey = (type: string, plural: boolean) =>
|
|
130
|
+
plural ? pluralize(cased(type)) : cased(type);
|
|
131
|
+
|
|
132
|
+
return {
|
|
133
|
+
updateMethod: 'put',
|
|
134
|
+
separatesRelationships: false,
|
|
135
|
+
keyError: (key) => keyError(keys, key),
|
|
136
|
+
relationshipKey: (key) => key,
|
|
137
|
+
path: options.path ?? ((type) => `/${pluralize(camelize(type))}`),
|
|
138
|
+
...sideloaded(rootKey),
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
interface Identifier {
|
|
143
|
+
type: string;
|
|
144
|
+
id: string;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function jsonApi(): Format {
|
|
148
|
+
const resourceType = (type: string) => pluralize(dasherize(type));
|
|
149
|
+
|
|
150
|
+
const identifier = (type: string, value: unknown): Identifier => {
|
|
151
|
+
if (value !== null && typeof value === 'object' && 'id' in value) {
|
|
152
|
+
const { type: explicit, id } = value as { type?: string; id: unknown };
|
|
153
|
+
return { type: resourceType(explicit ?? type), id: String(id) };
|
|
154
|
+
}
|
|
155
|
+
return { type: resourceType(type), id: String(value) };
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
const toLinkage = (
|
|
159
|
+
relationship: Relationship,
|
|
160
|
+
value: unknown,
|
|
161
|
+
): Identifier | Identifier[] | null => {
|
|
162
|
+
if (relationship.kind === 'hasMany') {
|
|
163
|
+
return ((value ?? []) as unknown[]).map((item) =>
|
|
164
|
+
identifier(relationship.type, item),
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
return value == null ? null : identifier(relationship.type, value);
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
return {
|
|
171
|
+
updateMethod: 'patch',
|
|
172
|
+
separatesRelationships: true,
|
|
173
|
+
keyError: (key) => keyError('dash', key),
|
|
174
|
+
relationshipKey: (key) => key,
|
|
175
|
+
path: (type) => `/${resourceType(type)}`,
|
|
176
|
+
|
|
177
|
+
document(type, data, extra, context) {
|
|
178
|
+
const many = Array.isArray(data);
|
|
179
|
+
const records = many ? data : [data];
|
|
180
|
+
const related = collect(records, context);
|
|
181
|
+
const present = new Set(
|
|
182
|
+
[...records.map((record) => ({ type, record })), ...related].map(
|
|
183
|
+
({ type: t, record }) => `${resourceType(t)}:${String(record.id)}`,
|
|
184
|
+
),
|
|
185
|
+
);
|
|
186
|
+
const isPresent = (linked: Identifier | Identifier[] | null) =>
|
|
187
|
+
linked === null ||
|
|
188
|
+
[linked].flat().every(({ type: t, id }) => present.has(`${t}:${id}`));
|
|
189
|
+
|
|
190
|
+
const resource = (resourceOf: string, record: BuiltRecord) => {
|
|
191
|
+
const { id, ...rest } = record;
|
|
192
|
+
const declared = context.relationships(record);
|
|
193
|
+
const attributes: Attrs = {};
|
|
194
|
+
const relationships: Attrs = {};
|
|
195
|
+
for (const [key, value] of Object.entries(rest)) {
|
|
196
|
+
const relationship = declared.get(key);
|
|
197
|
+
if (!relationship) {
|
|
198
|
+
attributes[key] = value;
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
const linked = toLinkage(relationship, value);
|
|
202
|
+
if (context.seeding || isPresent(linked)) {
|
|
203
|
+
relationships[key] = { data: linked };
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
return {
|
|
207
|
+
id: String(id),
|
|
208
|
+
type: resourceType(resourceOf),
|
|
209
|
+
attributes,
|
|
210
|
+
...(Object.keys(relationships).length ? { relationships } : {}),
|
|
211
|
+
};
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
return {
|
|
215
|
+
data: many
|
|
216
|
+
? records.map((record) => resource(type, record))
|
|
217
|
+
: resource(type, data),
|
|
218
|
+
...(related.length
|
|
219
|
+
? {
|
|
220
|
+
included: related.map(({ type: t, record }) =>
|
|
221
|
+
resource(t, record),
|
|
222
|
+
),
|
|
223
|
+
}
|
|
224
|
+
: {}),
|
|
225
|
+
...extra,
|
|
226
|
+
};
|
|
227
|
+
},
|
|
228
|
+
|
|
229
|
+
idFromBody: (_type, body) => idUnder(body, 'data'),
|
|
230
|
+
};
|
|
231
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export { HttpResponse, passthrough } from 'msw';
|
|
2
|
+
|
|
3
|
+
export { api, reply, type Call, type Handle } from './api.ts';
|
|
4
|
+
export { configure, type Options } from './config.ts';
|
|
5
|
+
export {
|
|
6
|
+
belongsTo,
|
|
7
|
+
build,
|
|
8
|
+
buildList,
|
|
9
|
+
defineFactory,
|
|
10
|
+
factoryOf,
|
|
11
|
+
fragment,
|
|
12
|
+
hasMany,
|
|
13
|
+
mergePayloads,
|
|
14
|
+
payload,
|
|
15
|
+
sequence,
|
|
16
|
+
sideload,
|
|
17
|
+
type FactoryDefinition,
|
|
18
|
+
} from './factories.ts';
|
|
19
|
+
export {
|
|
20
|
+
activeModel,
|
|
21
|
+
jsonApi,
|
|
22
|
+
rest,
|
|
23
|
+
type Format,
|
|
24
|
+
type RestOptions,
|
|
25
|
+
} from './formats.ts';
|
|
26
|
+
export { seed, seedList, seedRecord, sourceOf } from './store.ts';
|
|
27
|
+
export {
|
|
28
|
+
setupApplicationTest,
|
|
29
|
+
setupRenderingTest,
|
|
30
|
+
setupTest,
|
|
31
|
+
} from './setup.ts';
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import {
|
|
2
|
+
dependencySatisfies,
|
|
3
|
+
importSync,
|
|
4
|
+
macroCondition,
|
|
5
|
+
} from '@embroider/macros';
|
|
6
|
+
|
|
7
|
+
interface Inflector {
|
|
8
|
+
pluralize(word: string): string;
|
|
9
|
+
singularize(word: string): string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function appInflector(): Inflector {
|
|
13
|
+
if (
|
|
14
|
+
macroCondition(dependencySatisfies('@ember-data/request-utils', '>=5.3.0'))
|
|
15
|
+
) {
|
|
16
|
+
return importSync('@ember-data/request-utils/string') as Inflector;
|
|
17
|
+
} else if (macroCondition(dependencySatisfies('ember-inflector', '*'))) {
|
|
18
|
+
return importSync('ember-inflector') as Inflector;
|
|
19
|
+
}
|
|
20
|
+
return {
|
|
21
|
+
pluralize: (word) => `${word}s`,
|
|
22
|
+
singularize: (word) => word.replace(/s$/, ''),
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
let detected: Inflector | undefined;
|
|
27
|
+
|
|
28
|
+
export function pluralize(word: string): string {
|
|
29
|
+
return (detected ??= appInflector()).pluralize(word);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function singularize(word: string): string {
|
|
33
|
+
return (detected ??= appInflector()).singularize(word);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function underscore(word: string): string {
|
|
37
|
+
return word
|
|
38
|
+
.replace(/([a-z\d])([A-Z])/g, '$1_$2')
|
|
39
|
+
.replace(/-/g, '_')
|
|
40
|
+
.toLowerCase();
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function dasherize(word: string): string {
|
|
44
|
+
return underscore(word).replace(/_/g, '-');
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function camelize(word: string): string {
|
|
48
|
+
return word
|
|
49
|
+
.replace(/[-_\s]+(.)?/g, (_, next: string | undefined) =>
|
|
50
|
+
next ? next.toUpperCase() : '',
|
|
51
|
+
)
|
|
52
|
+
.replace(/^[A-Z]/, (first) => first.toLowerCase());
|
|
53
|
+
}
|
package/src/network.ts
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import {
|
|
2
|
+
buildWaiter,
|
|
3
|
+
getPendingWaiterState,
|
|
4
|
+
hasPendingWaiters,
|
|
5
|
+
} from '@ember/test-waiters';
|
|
6
|
+
import { FetchInterceptor } from '@mswjs/interceptors/fetch';
|
|
7
|
+
import { XMLHttpRequestInterceptor } from '@mswjs/interceptors/XMLHttpRequest';
|
|
8
|
+
import { http, HttpResponse, passthrough, type HttpHandler } from 'msw';
|
|
9
|
+
import { defineNetwork, InterceptorSource } from 'msw/experimental';
|
|
10
|
+
import * as QUnit from 'qunit';
|
|
11
|
+
|
|
12
|
+
import { installBeaconShim, removeBeaconShim } from './beacon.ts';
|
|
13
|
+
import {
|
|
14
|
+
afterTwoMacrotasks,
|
|
15
|
+
endOpenResponses,
|
|
16
|
+
installFetchWaiter,
|
|
17
|
+
nativeSetTimeout,
|
|
18
|
+
removeFetchWaiter,
|
|
19
|
+
unwrapStaleFetch,
|
|
20
|
+
} from './fetch-waiter.ts';
|
|
21
|
+
import { percyOrigin, settings } from './config.ts';
|
|
22
|
+
|
|
23
|
+
export interface NearMiss {
|
|
24
|
+
expected: Record<string, unknown>;
|
|
25
|
+
received: Record<string, unknown>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export const nearMisses = new Map<string, NearMiss[]>();
|
|
29
|
+
|
|
30
|
+
let reporter: (failure: Error) => void = (failure) =>
|
|
31
|
+
QUnit.onUncaughtException(failure);
|
|
32
|
+
|
|
33
|
+
export function setFailureReporter(next: (failure: Error) => void): () => void {
|
|
34
|
+
const previous = reporter;
|
|
35
|
+
reporter = next;
|
|
36
|
+
return () => {
|
|
37
|
+
reporter = previous;
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function reportFailure(failure: unknown): void {
|
|
42
|
+
reporter(failure instanceof Error ? failure : new Error(String(failure)));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function describe(value: unknown): string {
|
|
46
|
+
return JSON.stringify(
|
|
47
|
+
value,
|
|
48
|
+
(_key, item: unknown) =>
|
|
49
|
+
typeof item === 'function' ? '[predicate]' : item,
|
|
50
|
+
2,
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function describeNearMisses(requestId: string): string {
|
|
55
|
+
return (nearMisses.get(requestId) ?? [])
|
|
56
|
+
.map(({ expected, received }) => {
|
|
57
|
+
const actual = Object.fromEntries(
|
|
58
|
+
Object.keys(expected).map((key) => {
|
|
59
|
+
const value = received[key === 'partialQuery' ? 'query' : key];
|
|
60
|
+
return [
|
|
61
|
+
key,
|
|
62
|
+
key === 'headers'
|
|
63
|
+
? Object.fromEntries(
|
|
64
|
+
Object.keys(expected.headers as object).map((name) => [
|
|
65
|
+
name,
|
|
66
|
+
(value as Record<string, string>)[name] ?? null,
|
|
67
|
+
]),
|
|
68
|
+
)
|
|
69
|
+
: value,
|
|
70
|
+
];
|
|
71
|
+
}),
|
|
72
|
+
);
|
|
73
|
+
return `\nA handler for this URL expected ${describe(expected)}\nbut received ${describe(actual)}`;
|
|
74
|
+
})
|
|
75
|
+
.join('');
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function isBypassed(url: string): boolean {
|
|
79
|
+
if (!/^https?:/.test(url)) {
|
|
80
|
+
return true;
|
|
81
|
+
}
|
|
82
|
+
const { origin } = new URL(url);
|
|
83
|
+
const { bypass, bypassPercy } = settings();
|
|
84
|
+
return bypass.includes(origin) || (bypassPercy && origin === percyOrigin());
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const unhandled = http.all('*', ({ request, requestId }) => {
|
|
88
|
+
if (isBypassed(request.url)) {
|
|
89
|
+
return passthrough();
|
|
90
|
+
}
|
|
91
|
+
if (settings().appOrigins.includes(new URL(request.url).origin)) {
|
|
92
|
+
reportFailure(
|
|
93
|
+
new Error(
|
|
94
|
+
`No handler for ${request.method} ${request.url}${describeNearMisses(requestId)}`,
|
|
95
|
+
),
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
return new HttpResponse(null, { status: 404 });
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
const nativeNow = performance.now.bind(performance);
|
|
102
|
+
|
|
103
|
+
interface RequestEvent {
|
|
104
|
+
requestId: string;
|
|
105
|
+
request: Request;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const waiter = buildWaiter('ember-api-mocks:requests');
|
|
109
|
+
const pendingRequests = new Map<string, unknown>();
|
|
110
|
+
|
|
111
|
+
function startRequest(requestId: string, request: Request): void {
|
|
112
|
+
if (!isBypassed(request.url) && !pendingRequests.has(requestId)) {
|
|
113
|
+
pendingRequests.set(requestId, waiter.beginAsync());
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function endRequest(requestId: string): void {
|
|
118
|
+
if (pendingRequests.has(requestId)) {
|
|
119
|
+
waiter.endAsync(pendingRequests.get(requestId));
|
|
120
|
+
pendingRequests.delete(requestId);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export function finishRequest(requestId: string): void {
|
|
125
|
+
if (pendingRequests.has(requestId)) {
|
|
126
|
+
afterTwoMacrotasks(() => endRequest(requestId));
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function forgetPendingRequests(): void {
|
|
131
|
+
[...pendingRequests.keys()].forEach(endRequest);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function createNetwork() {
|
|
135
|
+
const created = defineNetwork({
|
|
136
|
+
sources: [
|
|
137
|
+
new InterceptorSource({
|
|
138
|
+
interceptors: [new XMLHttpRequestInterceptor(), new FetchInterceptor()],
|
|
139
|
+
}),
|
|
140
|
+
],
|
|
141
|
+
handlers: [unhandled],
|
|
142
|
+
onUnhandledFrame: 'bypass',
|
|
143
|
+
context: { quiet: true },
|
|
144
|
+
});
|
|
145
|
+
created.events.on('request:start', (event) => {
|
|
146
|
+
const { requestId, request } = event as RequestEvent;
|
|
147
|
+
startRequest(requestId, request);
|
|
148
|
+
});
|
|
149
|
+
created.events.on('request:end', (event) =>
|
|
150
|
+
finishRequest((event as RequestEvent).requestId),
|
|
151
|
+
);
|
|
152
|
+
return created;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
let instance: ReturnType<typeof createNetwork> | undefined;
|
|
156
|
+
|
|
157
|
+
function network(): ReturnType<typeof createNetwork> {
|
|
158
|
+
return (instance ??= createNetwork());
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export function useHandler(handler: HttpHandler): void {
|
|
162
|
+
network().use(handler);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export function enableNetwork(): void {
|
|
166
|
+
unwrapStaleFetch();
|
|
167
|
+
const original = globalThis.fetch;
|
|
168
|
+
network().enable();
|
|
169
|
+
installFetchWaiter(original, (url) => !isBypassed(url));
|
|
170
|
+
if (settings().beacons) {
|
|
171
|
+
installBeaconShim();
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export function disableNetwork(): void {
|
|
176
|
+
removeBeaconShim();
|
|
177
|
+
removeFetchWaiter();
|
|
178
|
+
network().resetHandlers();
|
|
179
|
+
network().disable();
|
|
180
|
+
forgetPendingRequests();
|
|
181
|
+
nearMisses.clear();
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const SETTLE_LIMIT_MS = 1000;
|
|
185
|
+
|
|
186
|
+
export async function settleRequests(): Promise<void> {
|
|
187
|
+
const deadline = nativeNow() + SETTLE_LIMIT_MS;
|
|
188
|
+
let quiet = 0;
|
|
189
|
+
while (quiet < 2 && nativeNow() < deadline) {
|
|
190
|
+
await new Promise((resolve) => nativeSetTimeout(resolve, 0));
|
|
191
|
+
quiet = pendingRequests.size === 0 && !hasPendingWaiters() ? quiet + 1 : 0;
|
|
192
|
+
}
|
|
193
|
+
if (quiet < 2) {
|
|
194
|
+
const names = Object.keys(getPendingWaiterState().waiters);
|
|
195
|
+
const others = names.filter((name) => !name.startsWith('ember-api-mocks:'));
|
|
196
|
+
reportFailure(
|
|
197
|
+
new Error(
|
|
198
|
+
others.length && others.length === names.length
|
|
199
|
+
? `Test waiters were still pending when the test ended: ${others.join(', ')}`
|
|
200
|
+
: 'Requests were still pending when the test ended',
|
|
201
|
+
),
|
|
202
|
+
);
|
|
203
|
+
}
|
|
204
|
+
forgetPendingRequests();
|
|
205
|
+
endOpenResponses();
|
|
206
|
+
}
|
package/src/setup.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import {
|
|
2
|
+
setupApplicationTest as upstreamSetupApplicationTest,
|
|
3
|
+
setupRenderingTest as upstreamSetupRenderingTest,
|
|
4
|
+
setupTest as upstreamSetupTest,
|
|
5
|
+
} from 'ember-qunit';
|
|
6
|
+
|
|
7
|
+
import { clearRequests } from './api.ts';
|
|
8
|
+
import { resetSequences } from './factories.ts';
|
|
9
|
+
import { disableNetwork, enableNetwork, settleRequests } from './network.ts';
|
|
10
|
+
|
|
11
|
+
type Setup = (hooks: NestedHooks, options?: object) => void;
|
|
12
|
+
|
|
13
|
+
function withApi(setup: Setup): Setup {
|
|
14
|
+
return function (hooks, options) {
|
|
15
|
+
hooks.beforeEach(function () {
|
|
16
|
+
resetSequences();
|
|
17
|
+
enableNetwork();
|
|
18
|
+
});
|
|
19
|
+
hooks.afterEach(function () {
|
|
20
|
+
disableNetwork();
|
|
21
|
+
clearRequests();
|
|
22
|
+
});
|
|
23
|
+
setup(hooks, options);
|
|
24
|
+
hooks.afterEach(settleRequests);
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export const setupApplicationTest = withApi(upstreamSetupApplicationTest);
|
|
29
|
+
export const setupRenderingTest = withApi(upstreamSetupRenderingTest);
|
|
30
|
+
export const setupTest = withApi(upstreamSetupTest);
|