### Install pusher-js-mock Source: https://github.com/nikolalsvk/pusher-js-mock/blob/master/README.md Instructions for installing the `pusher-js-mock` library as a development dependency using Yarn or npm. ```Shell yarn add --dev pusher-js-mock ``` ```Shell npm install -D pusher-js-mock ``` -------------------------------- ### Mocking Pusher Presence Channels with Custom Authorizer Source: https://github.com/nikolalsvk/pusher-js-mock/blob/master/README.md Shows how to create a Pusher client with a custom authorizer function and then test a presence channel. It includes examples of mocking dependencies like 'pusher-js' and a custom authentication helper. ```javascript // create-client.js import Pusher from "pusher-js"; import { getAuthSomehow } from "./getAuthSomehow"; export const createClient = ({ id, info }) => new Pusher("APP_KEY", { cluster: "APP_CLUSTER", // see https://github.com/pusher/pusher-js#authorizer-function authorizer: ({ name }) => ({ authorize: (socketId, callback) => { const auth = getAuthSomehow(id, info); callback(false, auth); } }) }); export default createClient; ``` ```javascript // create-client.spec.js import createClient from "../create-client"; // mock the authorize function and pusher jest.mock("pusher-js", () => require("pusher-js-mock")); jest.mock("../getAuthSomehow", () => ({ getAuthSomehow: (id, info) => ({ id, info }) })); it("should create a presence channel", async () => { // arrange: create pusher client const pusher = createClient({ id: "my-id", info: { role: "moderator" } }); // act: required to ensure pusher events are called, i.e. pusher:member_added const presenceChannel = await pusher.subscribe("presence-channel"); // assert: presenceChannel has the properties we expect it to. expect(presenceChannel.members.myID).toBe("my-id"); expect(presenceChannel.members.me).toEqual({ id: "my-id", info: { role: "moderator" } }); expect(presenceChannel.members.members).toEqual({ "my-id": { role: "moderator" } }); }); ``` -------------------------------- ### QueryLexer Prototype Methods (Core Lexing Operations) Source: https://github.com/nikolalsvk/pusher-js-mock/blob/master/docs/classes/pusherchannelmock.html Core methods for the `QueryLexer` prototype. These include `run` to start the lexing process, `sliceString` to extract the current lexeme, `emit` to add a lexeme to the list, `escapeCharacter` to handle escape sequences, `next` to advance the cursor, `width` to get current lexeme length, `ignore` to skip characters, `backup` to move back, `acceptDigitRun` to consume digits, and `more` to check for remaining input. ```javascript e.QueryLexer.prototype.run=function(){for(var t=e.QueryLexer.lexText;t;)t=t(this)},e.QueryLexer.prototype.sliceString=function(){for(var e=[],t=this.start,r=this.pos,i=0;i=this.length)return e.QueryLexer.EOS;var t=this.str.charAt(this.pos);return this.pos+=1,t},e.QueryLexer.prototype.width=function(){return this.pos-this.start},e.QueryLexer.prototype.ignore=function(){this.start==this.pos&&(this.pos+=1),this.start=this.pos},e.QueryLexer.prototype.backup=function(){this.pos-=1},e.QueryLexer.prototype.acceptDigitRun=function(){for(var t,r;47<(r=(t=this.next()).charCodeAt(0))&&r<58;);t!=e.QueryLexer.EOS&&this.backup()},e.QueryLexer.prototype.more=function(){return this.pos"===e[e.length-1]&&3<=e.length?[null,e,null]:L.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof k?t[0]:t,k.merge(this,k.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:E,!0)),D.test(r[1])&&k.isPlainObject(t))for(r in t)m(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=E.getElementById(r[2]))&&(this[0]=i,this.length=1),this}).prototype=k.fn,q=k(E); ``` -------------------------------- ### jQuery/k.fn.scrollLeft and scrollTop Methods Source: https://github.com/nikolalsvk/pusher-js-mock/blob/master/docs/classes/pusherchannelmock.html This code defines 'scrollLeft' and 'scrollTop' methods for jQuery-like objects, allowing users to get or set the horizontal and vertical scroll positions of elements or the document. It handles differences between window and document scrolling, providing a consistent API. ```JavaScript k.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;k.fn[t]=function(e){return _(this,function(e,t,n){var r;if(x(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}) ``` -------------------------------- ### Highlight.js Visual Studio Theme Source: https://github.com/nikolalsvk/pusher-js-mock/blob/master/docs/classes/pusherchannelmock.html CSS styles for Highlight.js, providing a Visual Studio-like syntax highlighting theme with specific color definitions for various code elements like comments, keywords, and tags. ```css .hljs { display: inline-block; padding: 0.5em; background: white; color: black; } .hljs-comment, .hljs-annotation, .hljs-template_comment, .diff .hljs-header, .hljs-chunk, .apache .hljs-cbracket { color: #008000; } .hljs-keyword, .hljs-id, .hljs-built_in, .css .smalltalk .hljs-class, .hljs-winutils, .bash .hljs-variable, .tex .hljs-command, .hljs-request, .hljs-status, .nginx .hljs-title { color: #00f; } .xml .hljs-tag { col ``` -------------------------------- ### Emit events on PusherMock channels Source: https://github.com/nikolalsvk/pusher-js-mock/blob/master/README.md Demonstrates how to initialize `PusherMock`, subscribe to a channel, and emit a custom event on that channel for testing purposes. ```JavaScript import { PusherMock } from "pusher-js-mock"; // initializing PusherMock const pusher = new PusherMock(); // subscribing to a Pusher channel const channel = pusher.subscribe("my-channel"); // emitting an event channel.emit("event-name"); ``` -------------------------------- ### jQuery.ajax() Core Implementation and Settings Source: https://github.com/nikolalsvk/pusher-js-mock/blob/master/docs/classes/pusherchannelmock.html This section details the internal implementation of jQuery's powerful `$.ajax()` function, including its default settings, prefilters, transports, and the core logic for making asynchronous HTTP requests. It covers how requests are configured, sent, and how responses are handled. ```APIDOC jQuery.extend({ active: 0, lastModified: {}, etag: {}, ajaxSettings: { url: "string", type: "string", // e.g., "GET", "POST" isLocal: "boolean", global: "boolean", processData: "boolean", async: "boolean", contentType: "string", // e.g., "application/x-www-form-urlencoded; charset=UTF-8" accepts: { "*": "*/*", text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /\\bxml\\b/, html: /\\bhtml/, json: /\\bjson\\b/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, converters: { "* text": "String", "text html": "true", "text json": "JSON.parse", "text xml": "k.parseXML" }, flatOptions: { url: true, context: true } }, ajaxSetup: function(e, t) { /* Merges default settings */ }, ajaxPrefilter: function(e, t) { /* Adds a prefilter function */ }, ajaxTransport: function(e, t) { /* Adds a transport function */ }, ajax: function(urlOrSettings, settings) { // Core AJAX request function // Parameters: // urlOrSettings: string (URL) or object (settings) // settings: object (optional, if urlOrSettings is URL) // // Returns: jqXHR object (a Promise-like object with additional methods) // // jqXHR Object Methods: // readyState: number (0: UNSENT, 1: OPENED, 2: HEADERS_RECEIVED, 3: LOADING, 4: DONE) // getResponseHeader(headerName: string): string | null // getAllResponseHeaders(): string | null // setRequestHeader(headerName: string, value: string): jqXHR // overrideMimeType(mimeType: string): jqXHR // statusCode(map: object): jqXHR // map: { statusCode: function, ... } // abort(statusText?: string): jqXHR // // jqXHR Deferred Methods (from jQuery.Deferred): // done(callbacks): jqXHR // fail(callbacks): jqXHR // always(callbacks): jqXHR // then(doneCallbacks, failCallbacks, progressCallbacks): Promise // promise(target): Promise } }); ``` -------------------------------- ### JavaScript k.event.special for Custom Event Behavior Source: https://github.com/nikolalsvk/pusher-js-mock/blob/master/docs/classes/pusherchannelmock.html Defines custom handling for specific event types, allowing for specialized setup, triggering, and delegation logic. This includes events like `click`, `load`, `focus`, `blur`, `mouseenter`, and `mouseleave` to ensure consistent behavior across different environments. ```javascript special:{load:{noBubble:!0},click:{setup:function(e){var t=this||e;return pe.test(t.type)&&t.click&&A(t,"input")&&De(t,"click",ke),!1},trigger:function(e){var t=this||e;return pe.test(t.type)&&t.click&&A(t,"input")&&De(t,"click"),!0},_default:function(e){var t=e.target;return pe.test(t.type)&&t.click&&A(t,"input")&&Q.get(t,"click")||A(t,"a")}},beforeunload:{postDispatch:function(e){void 0!==e.result&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}}}, k.each({focus:"focusin",blur:"focusout"},function(e,t){k.event.special[e]={setup:function(){return De(this,e,Ne),!1},trigger:function(){return De(this,e),!0},delegateType:t}}), k.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(e,i){k.event.special[e]={delegateType:i,bindType:i,handle:function(e){var t,n=e.relatedTarget,r=e.handleObj;return n&&(n===this||k.contains(this,n))||(e.type=r.origType,t=r.handler.apply(this,arguments),e.type=i),t}}}) ``` -------------------------------- ### APIDOC: PusherMockOptions Interface Source: https://github.com/nikolalsvk/pusher-js-mock/blob/master/docs/classes/pusherchannelmock.html Defines the optional configuration parameters that can be passed to the PusherMock constructor, mirroring some of the options available in the real Pusher.js client. ```APIDOC PusherMockOptions: cluster?: string The Pusher cluster to simulate (e.g., 'mt1'). forceTLS?: boolean Whether to force TLS connections. wsPort?: number The WebSocket port to simulate. wssPort?: number The secure WebSocket port to simulate. ``` -------------------------------- ### Form Element Value Handling: val method Source: https://github.com/nikolalsvk/pusher-js-mock/blob/master/docs/classes/pusherchannelmock.html The `val` method is used to get or set the value of form elements. When called without arguments, it retrieves the current value. When called with an argument, it sets the value of the selected elements. It handles various input types and can accept a function to determine the value. ```JavaScript k.fn.extend({val:function(n){var r,e,i,t=this[0];return arguments.length?(i=m(n),this.each(function(e){var t;1===this.nodeType&&(null==(t=i?n.call(this,e,k(this).val()):n)?t="":"number"==typeof t?t+="":Array.isArray(t)&&(t=k.map(t,function(e){return null==e?"":e+""})),(r=k.valHooks[this.type]||k.valHooks[this.nodeName.toLowerCase()])&&"set"in r&&void 0!==r.set(this,t,"value")||(this.value=t))})):t?(r=k.valHooks[t.type]||k.valHooks[t.nodeName.toLowerCase()])&&"get"in r&&void 0!==(e=r.get(t,"value"))?e:"string"==typeof(e=t.value)?e.replace(wt,""):null==e?"":e:void 0}}) ```