forked from jestjs/jest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jasmineAsyncInstall.ts
265 lines (233 loc) · 8.11 KB
/
jasmineAsyncInstall.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* This module adds ability to test async promise code with jasmine by
* returning a promise from `it/test` and `before/afterEach/All` blocks.
*/
import co from 'co';
import isGeneratorFn from 'is-generator-fn';
import pLimit = require('p-limit');
import type {Config, Global} from '@jest/types';
import isError from './isError';
import type Spec from './jasmine/Spec';
import type {DoneFn, QueueableFn} from './queueRunner';
import type {Jasmine} from './types';
function isPromise(obj: any): obj is PromiseLike<unknown> {
return obj && typeof obj.then === 'function';
}
// eslint-disable-next-line @typescript-eslint/no-empty-function
const doneFnNoop = () => {};
// eslint-disable-next-line @typescript-eslint/no-empty-function
doneFnNoop.fail = () => {};
function promisifyLifeCycleFunction(
originalFn: (beforeAllFunction: QueueableFn['fn'], timeout?: number) => void,
env: Jasmine['currentEnv_'],
) {
return function <T>(
fn:
| ((done: DoneFn) => void | PromiseLike<T>)
| (() => Promise<T>)
| GeneratorFunction
| undefined,
timeout?: number,
): void {
if (!fn) {
// @ts-expect-error: missing fn arg is handled by originalFn
return originalFn.call(env);
}
if (typeof fn !== 'function') {
// Pass non-functions to Jest, which throws a nice error.
return originalFn.call(env, fn, timeout);
}
const hasDoneCallback = fn.length > 0;
if (hasDoneCallback) {
// Give the function a name so it can be detected in call stacks, but
// otherwise Jasmine will handle it.
const asyncJestLifecycleWithCallback = function (
this: Global.TestContext,
...args: Array<any>
) {
// @ts-expect-error: Support possible extra args at runtime
return fn.apply(this, args);
};
return originalFn.call(env, asyncJestLifecycleWithCallback, timeout);
}
const extraError = new Error();
// Without this line v8 stores references to all closures
// in the stack in the Error object. This line stringifies the stack
// property to allow garbage-collecting objects on the stack
// https://crbug.com/v8/7142
// eslint-disable-next-line no-self-assign
extraError.stack = extraError.stack;
// We make *all* functions async and run `done` right away if they
// didn't return a promise.
const asyncJestLifecycle = function (done: DoneFn) {
const wrappedFn = isGeneratorFn(fn) ? co.wrap(fn) : fn;
const returnValue = wrappedFn.call({}, doneFnNoop);
if (isPromise(returnValue)) {
returnValue.then(done.bind(null, null), (error: Error) => {
const {isError: checkIsError, message} = isError(error);
if (message) {
extraError.message = message;
}
done.fail(checkIsError ? error : extraError);
});
} else {
done();
}
};
return originalFn.call(env, asyncJestLifecycle, timeout);
};
}
// Similar to promisifyLifeCycleFunction but throws an error
// when the return value is neither a Promise nor `undefined`
function promisifyIt(
originalFn: (
description: Global.TestNameLike,
fn: QueueableFn['fn'],
timeout?: number,
) => Spec,
env: Jasmine['currentEnv_'],
jasmine: Jasmine,
) {
return function (
specName: Global.TestNameLike,
fn?: (done: DoneFn) => void | PromiseLike<void>,
timeout?: number,
): Spec {
if (!fn) {
// @ts-expect-error: missing fn arg is handled by originalFn
const spec = originalFn.call(env, specName);
spec.pend('not implemented');
return spec;
}
if (typeof fn !== 'function') {
// Pass non-functions to Jest, which throws a nice error.
return originalFn.call(env, specName, fn, timeout);
}
const hasDoneCallback = fn.length > 0;
if (hasDoneCallback) {
// Give the function a name so it can be detected in call stacks, but
// otherwise Jasmine will handle it.
const asyncJestTestWithCallback = function (
this: Global.TestContext,
...args: Array<any>
) {
// @ts-expect-error: Support possible extra args at runtime
return fn.apply(this, args);
};
return originalFn.call(env, specName, asyncJestTestWithCallback, timeout);
}
const extraError = new Error();
// Without this line v8 stores references to all closures
// in the stack in the Error object. This line stringifies the stack
// property to allow garbage-collecting objects on the stack
// https://crbug.com/v8/7142
// eslint-disable-next-line no-self-assign
extraError.stack = extraError.stack;
const asyncJestTest = function (done: DoneFn) {
const wrappedFn = isGeneratorFn(fn) ? co.wrap(fn) : fn;
const returnValue = wrappedFn.call({}, doneFnNoop);
if (isPromise(returnValue)) {
returnValue.then(done.bind(null, null), (error: Error) => {
const {isError: checkIsError, message} = isError(error);
if (message) {
extraError.message = message;
}
if (jasmine.Spec.isPendingSpecException(error)) {
env.pending(message!);
done();
} else {
done.fail(checkIsError ? error : extraError);
}
});
} else if (returnValue === undefined) {
done();
} else {
done.fail(
new Error(
'Jest: `it` and `test` must return either a Promise or undefined.',
),
);
}
};
return originalFn.call(env, specName, asyncJestTest, timeout);
};
}
function makeConcurrent(
originalFn: (
description: Global.TestNameLike,
fn: QueueableFn['fn'],
timeout?: number,
) => Spec,
env: Jasmine['currentEnv_'],
mutex: ReturnType<typeof pLimit>,
): Global.ItConcurrentBase {
const concurrentFn = function (
specName: Global.TestNameLike,
fn: Global.ConcurrentTestFn,
timeout?: number,
) {
let promise: Promise<unknown> = Promise.resolve();
const spec = originalFn.call(env, specName, () => promise, timeout);
if (env != null && !env.specFilter(spec)) {
return spec;
}
try {
promise = mutex(() => {
const promise = fn();
if (isPromise(promise)) {
return promise;
}
throw new Error(
`Jest: concurrent test "${spec.getFullName()}" must return a Promise.`,
);
});
} catch (error) {
promise = Promise.reject(error);
}
// Avoid triggering the uncaught promise rejection handler in case the test errors before
// being awaited on.
// eslint-disable-next-line @typescript-eslint/no-empty-function
promise.catch(() => {});
return spec;
};
// each is bound after the function is made concurrent, so for now it is made noop
// eslint-disable-next-line @typescript-eslint/no-empty-function
concurrentFn.each = () => () => {};
concurrentFn.failing = () => () => {
throw new Error(
'Jest: `failing` tests are only supported in `jest-circus`.',
);
};
return concurrentFn;
}
export default function jasmineAsyncInstall(
globalConfig: Config.GlobalConfig,
global: Global.Global,
): void {
const jasmine = global.jasmine;
const mutex = pLimit(globalConfig.maxConcurrency);
const env = jasmine.getEnv();
env.it = promisifyIt(env.it, env, jasmine);
env.fit = promisifyIt(env.fit, env, jasmine);
global.it.concurrent = (env => {
const concurrent = makeConcurrent(
env.it,
env,
mutex,
) as Global.ItConcurrentExtended;
concurrent.only = makeConcurrent(env.fit, env, mutex);
concurrent.skip = makeConcurrent(env.xit, env, mutex);
return concurrent;
})(env);
global.fit.concurrent = makeConcurrent(env.fit, env, mutex);
env.afterAll = promisifyLifeCycleFunction(env.afterAll, env);
env.afterEach = promisifyLifeCycleFunction(env.afterEach, env);
env.beforeAll = promisifyLifeCycleFunction(env.beforeAll, env);
env.beforeEach = promisifyLifeCycleFunction(env.beforeEach, env);
}