Important, this middleware must always return a response because the ajax call to finalize_build is "async: false" and prevents testem from shutting down the browser until this response.
516560
function sendResponse(success) {
        success = success || false;
        response.status(200);
        response.contentType('application/json');
        response.send(JSON.stringify({success: success}));
      }
71635
function () {

    const oThis = this;

    const callback = async function (response) {
      if (response.isFailure()) {
        return response;
      }
      return responseHelper.successWithData({allTimeStakedAmount: response.data.getTotalStake});
    };

    return oThis._callMethod('getTotalStake').then(callback);

  }
824956
@Override
	public void finishStage(ResponseBuilder rb) {
		if (rb.req.getParams().getBool(MtasSolrSearchComponent.PARAM_MTAS, false)) {
			if (rb.stage >= ResponseBuilder.STAGE_EXECUTE_QUERY && rb.stage < ResponseBuilder.STAGE_GET_FIELDS) {
				for (ShardRequest sreq : rb.finished) {
					if (sreq.params.getBool(MtasSolrSearchComponent.PARAM_MTAS, false)
							&& sreq.params.getBool(PARAM_MTAS_VERSION, false)) {
						for (ShardResponse shardResponse : sreq.responses) {
							NamedList<Object> solrShardResponse = shardResponse.getSolrResponse().getResponse();
							try {
								SimpleOrderedMap<Object> data = (SimpleOrderedMap<Object>) solrShardResponse
										.findRecursive(MtasSolrSearchComponent.NAME, NAME);
								// create shardInfo
								SimpleOrderedMap<Object> dataShard = new SimpleOrderedMap<>();
								dataShard.add(NAME_MTAS_VERSION_SHARD, shardResponse.getShard());
								dataShard.add(NAME, data.clone());
								List<SimpleOrderedMap> dataShards = new ArrayList<>();
								dataShards.add(dataShard);
								// create main data
								data.clear();
								data.addAll(getVersion());
								// add shardInfo
								data.add(NAME_MTAS_VERSION_SHARDS, dataShards);
							} catch (ClassCastException | IOException e) {
								log.debug(e);
								// shouldn't happen
							}

						}
					}
				}

			}
		}

	}
1209497
function () {
        this.addResult = function (event) {
            var fullUrl = event.homeURL + url;
            http.get(fullUrl, function (response) {
                var content = "";
                response.on("data", function (chunk) {
                    content += chunk;
                });
                response.on("end", function () {
                    callback(content);
                });
            });
        };
        this.checkFinished = function () {
            return false;
        };
        events.EventEmitter.call(this);
    }
1111031
public void assertCorrectResonse(JSONObject response) throws JSONException {
		Integer lastHTTPResponseCode = getLastHTTPResponseCode();
		if(lastHTTPResponseCode != null) {
			//if a response code is set, check it. Selenium requests do not let you query this which is why we can't check this in case of a selenium API call
			assertEquals("The https response code should be 200 (OK)", new Integer(HttpURLConnection.HTTP_OK), lastHTTPResponseCode);
		}
		assertNotNull("The request should result in a response", response);	
	}
709610
function(response) {
      if (!this.xhr && this.config) {
        if (response) {
          this.xhr = true;
          var self = this;
          setTimeout(function() {
            APICall.complete(self, response);
          }, 1);
        } else {
          this.xhr = ajax(this.url, this.config);
        }
      }
      return this;
    }
232545
private static boolean finishLastResponse(final HttpConnection conn) {
        InputStream lastResponse = conn.getLastResponseInputStream();
        if(lastResponse != null) {
            conn.setLastResponseInputStream(null);
            try {
                lastResponse.close();
                return true;
            } catch (IOException ioe) {
                // force reconnect.
                return false;
            }
        } else {
            return false;
        }
    }
653202
function desiredResponse (context) {
  const callback = context.task.callbackManager.callbacks[context.executionName]
  return callback ? callback.eventName : COMPLETE
}
14428
private void ensureRespondJsScriptElement() {
		if (this.respondJsScript == null) {
			this.respondJsScript = Document.get().createScriptElement();
			this.respondJsScript.setSrc(GWT.getModuleBaseForStaticFiles() + DefaultIE8ThemeController.RESPOND_JS_LOCATION);
			this.respondJsScript.setType("text/javascript");
		}
	}
1061602
function () {
    const oThis = this;

    return oThis.asyncPerform()
      .catch(function (error) {
        if (responseHelper.isCustomResult(error)) {
          return error;
        } else {
          logger.error('openst-platform::services/approve/branded_token.js::perform::catch');
          logger.error(error);

          return responseHelper.error({
            internal_error_identifier: 's_a_bt_1',
            api_error_identifier: 'unhandled_error',
            error_config: basicHelper.fetchErrorConfig()
          });
        }
      });
  }
697038
function forceEnd(path, response) {

            // Send a custom response for gateway timeout
            new $CustomResponse().head(504, null, {
                'Content-Type': 'text/html'
            }).writeSync(`<h1>${RESPONSE_HEADER_MESSAGES[ 504 ]}</h1>`);

            // Log something
            $LogProvider.error(path, response._header);

            // End the response
            end(response);
        }
219844
async def wait_for_body_middleware(environ, start_response=None):
    '''
    '''
    if environ.get('wsgi.async'):
        try:
            chunk = await environ['wsgi.input'].read()
        except TypeError:
            chunk = b''
        environ['wsgi.input'] = BytesIO(chunk)
        environ.pop('wsgi.async')
1189697
async function beforeHook(done) {
    // height & width : 100%
    fullScreen();
    if (initialled) return done && done();
    let { url, host, port } = _config;
    if (!url) url = host + ':' + port;
    await loadScript('//' + url + '/socket.io/socket.io.js');
    // it's hard to share socket with karma
    // Connection = (opener || parent).karma.socket;
    Connection = io(url);
    Connection.on('runBack', (message) => {
        // console.log('runBack', message);
        message && !message.status ? serialPromiseResolve() : serialPromiseReject(message.status);
    });
    // whether there is contextFrame, wait
    waitingPromise = wrapPromise((resolve) => {
        Connection.on('ready', (message) => {
            let { supportedDefs = '' } = message;
            supportedDefs.split(' ').map((def) => {
                $$Browser[def] = function () {
                    return this.__toRunnable(def, ...arguments);
                };
            });
            // console.log('ready', message);
            routePCToMobile();
            resolve();
        });
    });
    await waitingPromise;
    initialled = true;
    done && done();
}
1003175
def _BuildResponse(self,
                     status,
                     rendered_data,
                     method_name=None,
                     headers=None,
                     content_length=None,
                     token=None,
                     no_audit_log=False):
    """"""

    # To avoid IE content sniffing problems, escape the tags. Otherwise somebody
    # may send a link with malicious payload that will be opened in IE (which
    # does content sniffing and doesn't respect Content-Disposition header) and
    # IE will treat the document as html and executre arbitrary JS that was
    # passed with the payload.
    str_data = json.Dump(
        rendered_data, encoder=JSONEncoderWithRDFPrimitivesSupport)
    # XSSI protection and tags escaping
    rendered_data = ")]}'\n" + str_data.replace("<", r"\u003c").replace(
        ">", r"\u003e")

    response = werkzeug_wrappers.Response(
        rendered_data,
        status=status,
        content_type="application/json; charset=utf-8")
    response.headers[
        "Content-Disposition"] = "attachment; filename=response.json"
    response.headers["X-Content-Type-Options"] = "nosniff"

    if token and token.reason:
      response.headers["X-GRR-Reason"] = utils.SmartStr(token.reason)
    if method_name:
      response.headers["X-API-Method"] = method_name
    if no_audit_log:
      response.headers["X-No-Log"] = "True"

    for key, value in iteritems(headers or {}):
      response.headers[key] = value

    if content_length is not None:
      response.content_length = content_length

    return response
116406
function () {

            var res = arguments[0];

            userOptions.emit('response', req, res);

            if (callback && userOptions.resCallback) callback.apply(this, arguments);

            res.on('end', function() {
                userOptions.emit('afterResponse', req, res);
            });

        }
332820
async function runExample() {
	let browser;
	let pages;
	try {

		// Launch our own browser
		browser = await puppeteer.launch();

		// Create a page for the test runs
		// (Pages cannot be used in multiple runs)
		pages = [
			await browser.newPage(),
			await browser.newPage()
		];

		// Test http://example.com/ with our shared browser
		const result1 = await pa11y('http://example.com/', {
			browser: browser,
			page: pages[0]
		});

		// Test http://example.com/otherpage/ with our shared browser
		const result2 = await pa11y('http://example.com/otherpage/', {
			browser: browser,
			page: pages[1]
		});

		// Output the raw result objects
		console.log(result1);
		console.log(result2);

		// Close the browser instance and pages now we're done with it
		for (const page of pages) {
			await page.close();
		}
		await browser.close();

	} catch (error) {

		// Output an error if it occurred
		console.error(error.message);

		// Close the browser instance and pages if theys exist
		if (pages) {
			for (const page of pages) {
				await page.close();
			}
		}
		if (browser) {
			await browser.close();
		}

	}
}
310981
function() {
            var i, responseType;
            // Stop sending state
            sending = false;
            clearTimeout(timeout);
            // Launch next stacked request
            if(request_stack.length) {
                request_stack.shift().send();
            }
            // Verify if the request has not been previously aborted
            if(aborted) {
                return;
            }
            // Decrease the number of requests
            --requests;
            // Handle response
            try{
                // Process response
                if(nativeResponseParsing) {
                    if('response' in xhr && xhr.response === null) {
                        throw 'The request response is empty';
                    }
                    response = xhr.response;
                }
                else {
                    // Guess response type
                    responseType = options.responseType;
                    if(responseType == 'auto') {
                        if(xdr) {
                            responseType = defaultXdrResponseType;
                        }
                        else {
                            var ct = xhr.getResponseHeader('Content-Type') || '';
                            if(ct.indexOf(mimeTypes.json)>-1) {
                                responseType = 'json';
                            }
                            else if(ct.indexOf(mimeTypes.xml) > -1) {
                                responseType = 'xml';
                            }
                            else {
                                responseType = 'text';
                            }
                        }
                    }
                    // Handle response type
                    switch(responseType) {
                        case 'json':
                            if(xhr.responseText.length) {
                                try {
                                    if('JSON' in global) {
                                        response = JSON.parse(xhr.responseText);
                                    }
                                    else {
                                        response = new Function('return (' + xhr.responseText + ')')();
                                    }
                                }
                                catch(e) {
                                    throw "Error while parsing JSON body : "+e;
                                }
                            }
                            break;
                        case 'xml':
                            // Based on jQuery's parseXML() function
                            try {
                                // Standard
                                if(global.DOMParser) {
                                    response = (new DOMParser()).parseFromString(xhr.responseText,'text/xml');
                                }
                                // IE<9
                                else {
                                    response = new ActiveXObject('Microsoft.XMLDOM');
                                    response.async = 'false';
                                    response.loadXML(xhr.responseText);
                                }
                            }
                            catch(e) {
                                response = undefined;
                            }
                            if(!response || !response.documentElement || response.getElementsByTagName('parsererror').length) {
                                throw 'Invalid XML';
                            }
                            break;
                        default:
                            response = xhr.responseText;
                    }
                }
                // Late status code verification to allow passing data when, per example, a 409 is returned
                // --- https://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request
                if('status' in xhr && !/^2|1223/.test(xhr.status)) {
                    throw xhr.status + ' (' + xhr.statusText + ')';
                }
                // Fulfilled
                promise(true, [xhr, response]);
            }
            catch(e) {
                // Rejected
                promise(false, [e, xhr, response]);
            }
        }