UNPKG

2.18 kBJavaScriptView Raw
1/* global afterEach, jasmine */
2var pendingPromisesForTheCurrentTest = [];
3var afterEachRegistered = false;
4
5var currentSpec = null;
6
7if (typeof jasmine === 'object') {
8 // Add a custom reporter that allows us to capture the name of the currently executing spec:
9 jasmine.getEnv().addReporter({
10 specStarted: function specStarted(spec) {
11 currentSpec = spec;
12 },
13 specDone: function specDone(spec) {
14 currentSpec = null;
15 }
16 });
17}
18
19function isPendingOrHasUnhandledRejection(promise) {
20 return (
21 !promise._fulfillmentHandler0 &&
22 !promise._rejectionHandler0 &&
23 !promise._receiver0 &&
24 (promise.isPending() || (promise.isRejected() && promise.reason().uncaught))
25 );
26}
27
28function registerAfterEachHook() {
29 if (typeof afterEach === 'function' && !afterEachRegistered) {
30 afterEachRegistered = true;
31 try {
32 afterEach(function() {
33 var error;
34 var testPassed = true;
35 if (
36 pendingPromisesForTheCurrentTest.some(
37 isPendingOrHasUnhandledRejection
38 )
39 ) {
40 var displayName;
41 if (this.currentTest) {
42 // mocha
43 testPassed = this.currentTest.state === 'passed';
44 displayName = this.currentTest.title;
45 } else if (typeof currentSpec === 'object') {
46 testPassed = currentSpec.failedExpectations.length === 0;
47 displayName = currentSpec.fullName;
48 }
49 error = new Error(
50 (displayName + ": You have created a promise that was not returned from the it block")
51 );
52 }
53 pendingPromisesForTheCurrentTest = [];
54 if (error && testPassed) {
55 throw error;
56 }
57 });
58 } catch (e) {
59 // The benchmark suite fails when attempting to add an afterEach
60 }
61 }
62}
63
64// When running in jasmine/node.js, afterEach is available immediately,
65// but doesn't work within the it block. Register the hook immediately:
66registerAfterEachHook();
67
68module.exports = function notifyPendingPromise(promise) {
69 pendingPromisesForTheCurrentTest.push(promise);
70 // Register the afterEach hook lazily (mocha/node.js):
71 registerAfterEachHook();
72};