New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

mock-xmlhttprequest

Package Overview
Dependencies
Maintainers
1
Versions
35
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

mock-xmlhttprequest - npm Package Compare versions

Comparing version 8.1.0 to 8.2.0

7

dist/types/MockXhr.d.ts

@@ -5,4 +5,4 @@ import MockXhrRequest from './MockXhrRequest';

import type { MockXhrResponseReceiver } from './MockXhrResponseReceiver';
export declare type OnCreateCallback = (xhr: MockXhr) => void;
export declare type OnSendCallback = (this: MockXhrRequest, request: MockXhrRequest) => void;
export type OnCreateCallback = (xhr: MockXhr) => void;
export type OnSendCallback = (this: MockXhrRequest, request: MockXhrRequest, xhr: MockXhr) => void;
/**

@@ -115,5 +115,6 @@ * XMLHttpRequest mock for testing.

* @param receivedBytesLength Received bytes' length
* @param length Body length in bytes
* @see {@link https://xhr.spec.whatwg.org/#the-send()-method "processBodyChunk" steps}
*/
downloadProgress(request: RequestData, receivedBytesLength: number): void;
downloadProgress(request: RequestData, receivedBytesLength: number, length: number): void;
/**

@@ -120,0 +121,0 @@ * Set the response body. Changes the request's readyState to DONE.

@@ -42,6 +42,6 @@ import RequestData from './RequestData';

*
* @param status Response http status (default 200)
* @param status Response HTTP status (default 200)
* @param headers Name-value headers (optional)
* @param body Response body (default null)
* @param statusText Response http status text (optional)
* @param statusText Response HTTP status text (optional)
*/

@@ -52,5 +52,5 @@ respond(status?: number, headers?: Record<string, string> | null, body?: any, statusText?: string): void;

*
* @param status Response http status (default 200)
* @param status Response HTTP status (default 200)
* @param headers Name-value headers (optional)
* @param statusText Response http status text (optional)
* @param statusText Response HTTP status text (optional)
*/

@@ -62,4 +62,5 @@ setResponseHeaders(status?: number, headers?: Record<string, string> | null, statusText?: string): void;

* @param transmitted Transmitted bytes
* @param length Body length in bytes
*/
downloadProgress(transmitted: number): void;
downloadProgress(transmitted: number, length: number): void;
/**

@@ -66,0 +67,0 @@ * Set the response body. Changes the request's readyState to DONE.

@@ -8,3 +8,3 @@ import type RequestData from './RequestData';

setResponseHeaders(request: RequestData, status?: number, headers?: Record<string, string> | null, statusText?: string): void;
downloadProgress(request: RequestData, receivedBytesLength: number): void;
downloadProgress(request: RequestData, receivedBytesLength: number, length: number): void;
setResponseBody(request: RequestData, body: any): void;

@@ -11,0 +11,0 @@ setNetworkError(request: RequestData): void;

import MockXhr from './MockXhr';
import type MockXhrRequest from './MockXhrRequest';
export declare type UrlMatcher = ((url: string) => boolean) | string | RegExp;
export type UrlMatcher = ((url: string) => boolean) | string | RegExp;
export interface RequestHandlerResponse {

@@ -10,5 +10,5 @@ status: number;

}
declare type RequestHandlerCallback = (request: MockXhrRequest) => void;
declare type SingleRequestHandler = Partial<RequestHandlerResponse> | RequestHandlerCallback | 'error' | 'timeout';
export declare type RequestHandler = SingleRequestHandler | SingleRequestHandler[];
type RequestHandlerCallback = (request: MockXhrRequest) => void;
type SingleRequestHandler = Partial<RequestHandlerResponse> | RequestHandlerCallback | 'error' | 'timeout';
export type RequestHandler = SingleRequestHandler | SingleRequestHandler[];
interface RequestLogEntry {

@@ -69,8 +69,12 @@ method: string;

* Disable the effects of the timeout attribute on the XMLHttpRequest mock used by the server.
*
* @returns this
*/
disableTimeout(): void;
disableTimeout(): this;
/**
* Enable the effects of the timeout attribute on the XMLHttpRequest mock used by the server.
*
* @returns this
*/
enableTimeout(): void;
enableTimeout(): this;
/**

@@ -77,0 +81,0 @@ * Add a GET request handler.

@@ -47,14 +47,2 @@ export declare function getBodyByteSize(body?: string | FormData | Blob | BufferSource | null): number;

export declare function getStatusText(status: number): string;
/**
* @param headerValue Header value
* @returns Split header value list or null
* @see {@link https://fetch.spec.whatwg.org/#concept-header-list-get-decode-split}
*/
export declare function decodeAndSplitHeaderValue(headerValue: string | null): string[] | null;
/**
* @param headerValue Header value
* @returns Extracted length, null, or false (failure)
* @see {@link https://fetch.spec.whatwg.org/#header-list-extract-a-length}
*/
export declare function extractLengthFromHeader(headerValue: string | null): number | false | null;
//# sourceMappingURL=Utils.d.ts.map

@@ -61,4 +61,4 @@ /**

}
declare type EventHandlerProperty = ((this: XMLHttpRequest, ev: ProgressEvent) => any);
type EventHandlerProperty = ((this: XMLHttpRequest, ev: ProgressEvent) => any);
export {};
//# sourceMappingURL=XhrEventTarget.d.ts.map
export declare const XHR_PROGRESS_EVENT_NAMES: readonly ["loadstart", "progress", "abort", "error", "load", "timeout", "loadend"];
export declare type TXhrProgressEventNames = typeof XHR_PROGRESS_EVENT_NAMES[number];
export type TXhrProgressEventNames = typeof XHR_PROGRESS_EVENT_NAMES[number];
//# sourceMappingURL=XhrProgressEventsNames.d.ts.map
{
"name": "mock-xmlhttprequest",
"version": "8.1.0",
"version": "8.2.0",
"description": "XMLHttpRequest mock for testing",

@@ -51,5 +51,5 @@ "exports": {

"devDependencies": {
"@rollup/plugin-typescript": "^8.3.3",
"@rollup/plugin-typescript": "^9.0.0",
"@types/chai": "^4.3.1",
"@types/mocha": "^9.1.1",
"@types/mocha": "^10.0.0",
"@types/node": "^18.6.0",

@@ -66,3 +66,3 @@ "@typescript-eslint/eslint-plugin": "^5.13.0",

"rimraf": "^3.0.2",
"rollup": "^2.47.0",
"rollup": "^3.2.3",
"ts-node": "^10.8.2",

@@ -69,0 +69,0 @@ "typescript": "^4.7.3"

@@ -11,3 +11,3 @@ [![Build Status](https://app.travis-ci.com/berniegp/mock-xmlhttprequest.svg?branch=master)](https://app.travis-ci.com/berniegp/mock-xmlhttprequest)

You can simulate responses, upload progress, errors, and other interactions with the [mock response methods](#mock-response-methods). These automatically handle lower-level processing like emitting events and changing the `readystate` property of `XMLHttpRequest`.
You can simulate responses, upload progress, errors, and other interactions with the [mock response methods](#mock-response-methods). These automatically handle lower-level processing such as emitting events and changing the `readystate` property of `XMLHttpRequest`.

@@ -211,10 +211,15 @@ ## Table of contents

### `MockXhrServer` class
This class is a mock server that responds to `MockXhr` requests.
This class is a mock server that responds to `MockXhr` requests based on their URL and method.
#### `MockXhrServer` setup
##### `MockXhrServer(routes)`
Arguments:
- `routes`: Object with the initial set of [routes](#routes) of the server. (optional)
In most cases you should use [`newServer`](#newserverroutes) instead of this constructor directly.
Add an initial set of [routes](#routes) to a `MockXhrServer` with the optional `routes` argument. The property keys of the `routes` object are HTTP methods. Each corresponding value is a two-element array containing `[url_matcher, request_handler]`. See also [Request URL matcher](#request-url-matcher) and [Request handler](#request-handler).
The keys of the `routes` object are HTTP methods. The values are arrays with two elements: `[url_matcher, request_handler]`.
See also [Request URL matcher](#request-url-matcher) and [Request handler](#request-handler).
Example:

@@ -231,4 +236,7 @@ ```javascript

##### `install(context = globalThis)`
Installs the server's `MockXhr` mock in the global context to replace the `XMLHttpRequest` class. Specify a different context with the optional `context` argument. Revert with [remove()](#remove).
Arguments:
- `context`: If you provide a value, the `install` method sets the `XMLHttpRequest` property in this context instead of the global context. (optional)
Installs the server's `MockXhr` mock in the global context to replace the `XMLHttpRequest` class. Revert with [remove()](#remove).
##### `remove()`

@@ -238,3 +246,3 @@ Reverts the changes made by [install()](#installcontext--globalthis). Call this after your tests.

##### `progressRate`
If you set this to a value greater than 0, the server automatically generates request (upload) and response (download) progress events. The progress events have increments of `progressRate` bytes.
If you set `progressRate` to a `number` greater than 0, the server automatically generates request (upload) and response (download) progress events. Each progress event increments by `progressRate` bytes.

@@ -244,6 +252,6 @@ `progressRate` only applies to [request handlers](#request-handler) of type `object`.

##### `disableTimeout()` and `enableTimeout()`
Controls whether the `timeout` attribute of a `MockXhr` instance can trigger `timeout` events. See ["The `timeout` attribute and request timeouts"](#the-timeout-attribute-and-request-timeouts).
These methods disable or enable the effects of the `timeout` attribute of `MockXhr`. See ["The `timeout` attribute and request timeouts"](#the-timeout-attribute-and-request-timeouts).
#### Routes
Routes respond to `MockXhr` requests and have three parts described below.
Routes configure how the server responds to `MockXhr` requests. Their three parts are described below.

@@ -253,6 +261,6 @@ The route concept is loosely based on the [Express framework](https://expressjs.com/).

##### HTTP request method
Any `string` with a valid [HTTP request method](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods) is allowed. This includes standard methods like `GET`, `POST`, `PUT` and `DELETE`, but also other method names. The standard method names are case insensitive.
Any `string` with a valid [HTTP request method](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods) is allowed. The valid methods include standard methods such as `GET`, `POST`, `PUT` and `DELETE`, as well as other method names. The standard method names are case insensitive.
##### Request URL matcher
This supports three options:
The request URL matcher can be one of these types:
- A `string` (e.g. `'/my-url'`) to match the request's URL exactly.

@@ -263,3 +271,3 @@ - A `RegExp` to match the request's URL.

##### Request handler
This supports three options:
The request handler can be one of these types:
- An `object` with the response properties. The default values are:

@@ -270,5 +278,5 @@

- A `string` with the value `'error'` or `'timeout'`. This triggers either an [error](#setnetworkerror) or [timeout](#setrequesttimeout) respectively.
- An array of the request handler options above. The first request gets the first handler, the second gets the second handler and so on. The last handler is reused when there are more requests than handlers.
- An array of the other request handler types above. The first request gets the first handler, the second gets the second handler and so on. The last handler is reused when there are no further handlers in the array.
For `object` request handlers, the server automatically adds the `Content-Length` response header with a value equal to the length of the response body.
For `object` request handlers, the server automatically adds the `Content-Length` response header with the length of the response body.

@@ -284,17 +292,41 @@ All these handlers are equivalent:

##### `get(urlMatcher, handler)`
Arguments:
- `urlMatcher`: [Request URL matcher](#request-url-matcher).
- `handler`: [Request handler](#request-handler).
Adds a [route](#routes) for the `GET` HTTP method.
##### `post(urlMatcher, handler)`
Arguments:
- `urlMatcher`: [Request URL matcher](#request-url-matcher).
- `handler`: [Request handler](#request-handler).
Adds a [route](#routes) for the `POST` HTTP method.
##### `put(urlMatcher, handler)`
Arguments:
- `urlMatcher`: [Request URL matcher](#request-url-matcher).
- `handler`: [Request handler](#request-handler).
Adds a [route](#routes) for the `PUT` HTTP method.
##### `delete(urlMatcher, handler)`
Arguments:
- `urlMatcher`: [Request URL matcher](#request-url-matcher).
- `handler`: [Request handler](#request-handler).
Adds a [route](#routes) for the `DELETE` HTTP method.
##### `addHandler(method, urlMatcher, handler)`
Arguments:
- `method`: HTTP method as a `string`.
- `urlMatcher`: [Request URL matcher](#request-url-matcher).
- `handler`: [Request handler](#request-handler).
Adds a [route](#routes) for the `method` HTTP method.
##### `setDefaultHandler(handler)`
Arguments:
- `handler`: [Request handler](#request-handler).
Sets a default request handler for requests that don't match any route.

@@ -310,6 +342,6 @@

##### `MockXhr`
The `MockXhr` class that the server handles. This is the class of the instances created by [`xhrFactory`](#xhrfactory).
The `MockXhr` class that the server hooks into. [`xhrFactory`](#xhrfactory) creates instances of this class.
##### `getRequestLog()`
Returns an array of all requests received by the server so far. Each array element is an object with these properties:
Returns an array of all requests received by the server so far. Each call returns a new array. Each array element is an object with these properties:
- `method`: HTTP method `string`.

@@ -325,6 +357,6 @@ - `url`: URL `string`.

##### `MockXhr.timeoutEnabled`
This static property controls [automatic timeout](#the-timeout-attribute-and-request-timeouts) of requests of all instances of the class.
This static `boolean` property controls [automatic timeout](#the-timeout-attribute-and-request-timeouts) of requests from all instances of the class.
##### `timeoutEnabled`
This property controls [automatic timeout](#the-timeout-attribute-and-request-timeouts) of this `MockXhr` instance.
This `boolean` property controls [automatic timeout](#the-timeout-attribute-and-request-timeouts) from this `MockXhr` instance.

@@ -335,17 +367,18 @@ ##### `getResponseHeadersHash()`

#### `MockXhr` lifecycle hooks
The `MockXhr` lifecycle hooks can be configured at these locations:
1. A static property on the `MockXhr` class. This affects all instances of `MockXhr` and all its subclasses.
2. A static property on a `MockXhr` subclass as exposed by [`MockXhrServer.MockXhr`](#mockxhr) or returned by [`newMockXhr()`](#newmockxhr). This affects all instances of that class.
3. A property on an instance of `MockXhr`. This affects that instance only.
You can define callback methods for the `MockXhr` lifecycle hooks at these locations:
1. A static property on the `MockXhr` class. The hook applies to all instances of `MockXhr` and of its subclasses.
2. A static property on a `MockXhr` subclass returned by [`MockXhrServer.MockXhr`](#mockxhr) or [`newMockXhr()`](#newmockxhr). The hook applies to all instances of that class.
3. A property on an instance of `MockXhr`. The hook applies to that instance only.
If you define multiple hooks for a lifecycle event, they are called in the order from the list above.
If you define multiple hooks for a lifecycle event, they are called in the order above.
You should generally prefer the third option over the second one because it makes it easier to isolate your test cases.
You should generally prefer the third option which makes it easier to isolate your test cases.
##### `onCreate`
Called when an instance of `MockXhr` is created, at the end of its constructor. The hook function receives the created `MockXhr` as an argument.
Callback method that receives these arguments:
- `xhr`: New `MockXhr` instance.
Use this lifecycle hook to intercept instances of `MockXhr` when they are constructed.
This lifecycle hook does not exist as a `MockXhr` instance property because it is called as part of an instance's constructor.
Called when an instance of `MockXhr` is created, at the end of its constructor. This lifecycle hook is therefore only available as a static property.

@@ -364,6 +397,10 @@ ```javascript

##### `onSend`
Called [asynchronously](#asynchronous-responses) after each call to `send()`. Each call to `send()` generates a call to `onSend` with a matching [`MockXhrRequest`](#mockxhrrequest-class) instance as an argument.
Callback method that receives these arguments:
- `request`: [`MockXhrRequest`](#mockxhrrequest-class) for the request.
- `xhr`: The `MockXhr` instance.
Use this lifecycle hook to respond to a request with the [mock response methods](#mock-response-methods).
Called [asynchronously](#asynchronous-responses) after each call to `send()`. Each call to `send()` generates a call to `onSend` with a separate instance of [`MockXhrRequest`](#mockxhrrequest-class).
```javascript

@@ -385,13 +422,13 @@ import { MockXhr, newMockXhr } from 'mock-xmlhttprequest';

### `MockXhrRequest` class
This class encapsulates an `XMLHttpRequest` request when you call `send()` and provides methods to respond to it programmatically.
Each call to `send()` creates a `MockXhrRequest` that contains information about the `XMLHttpRequest` and provides methods to respond programmatically.
#### Request data
##### `requestHeaders`
A copy of the request's headers. This is an instance of `HeadersContainer`.
A `HeadersContainer` that contains a copy of the request's headers.
##### `method`
The request's HTTP method.
A `string` with the request's HTTP method.
##### `url`
The request's URL.
A `string` with the request's URL.

@@ -402,6 +439,6 @@ ##### `body`

##### `withCredentials`
The request's `withCredentials` value.
A `boolean` with the request's `withCredentials` value.
##### `getRequestBodySize()`
The request's body size in bytes.
`number` of bytes in the request body.

@@ -413,7 +450,10 @@ Note: this isn't completely accurate when the `body` is a `multipart/form-data` encoded `FormData`. Headers, encoding, and other factors that contribute to a non-mocked `XMLHttpRequest`'s true `body` size are not considered. You can use this method to get a floor value for the request's true `body` size. This is useful to simulate upload progress events.

If a call to a response method is invalid, it throws an `Error` with a message that contains "Mock usage error detected".
If a call to a response method is invalid, it throws an `Error` with a message that contains `"Mock usage error detected"`.
##### `uploadProgress(transmitted)`
Fires a request upload progress event where `transmitted` is the number of bytes transmitted.
Arguments:
- `transmitted`: `number` of bytes transmitted.
Fires a request upload progress.
You can only call this when the request's `body` isn't `null` and the upload isn't complete.

@@ -424,2 +464,8 @@

##### `respond(status = 200, headers = {}, body = null, statusText = 'OK')`
Arguments:
- `status`: Response HTTP status `number`. (optional)
- `headers`: `object` with the response headers. (optional)
- `body`: Response body. (optional)
- `statusText`: `string` response HTTP status text. (optional)
Complete response method that sets both the response headers and body. Changes the request's `readyState` to `DONE`.

@@ -434,2 +480,7 @@

##### `setResponseHeaders(status = 200, headers = {}, statusText = 'OK')`
Arguments:
- `status`: Response HTTP status `number`. (optional)
- `headers`: `object` with the response headers. (optional)
- `statusText`: `string` response HTTP status text. (optional)
Sets the response headers. Changes the request's `readyState` to `HEADERS_RECEIVED`.

@@ -440,3 +491,3 @@

After you call this method, you can use the following mock response methods:
- [`downloadProgress()`](#downloadprogresstransmitted)
- [`downloadProgress()`](#downloadprogresstransmitted-length)
- [`setResponseBody()`](#setresponsebodybody--null)

@@ -446,3 +497,7 @@ - [`setNetworkError()`](#setnetworkerror)

##### `downloadProgress(transmitted)`
##### `downloadProgress(transmitted, length)`
Arguments:
- `transmitted`: `number` of bytes transmitted.
- `length`: `number` of bytes in the response.
Fires a response progress event. Changes the request's `readyState` to `LOADING` if it is `HEADERS_RECEIVED`.

@@ -453,2 +508,5 @@

##### `setResponseBody(body = null)`
Arguments:
- `body`: Response body. (optional)
Sets the response body. Changes the request's `readyState` to `DONE`.

@@ -484,2 +542,5 @@

### `newServer(routes)`
Arguments:
- `routes`: Object with the initial set of [routes](#routes) of the server. (optional)
Returns a new `MockXhrServer` with its own unique `MockXhr` subclass. See [`newMockXhr()`](#newmockxhr).

@@ -495,3 +556,3 @@

- `open()`, `setRequestHeader()`, `send()` and `abort()`.
- [Upload](#uploadprogresstransmitted) and [download](#downloadprogresstransmitted) progress events.
- [Upload](#uploadprogresstransmitted) and [download](#downloadprogresstransmitted-length) progress events.
- Response status, `statusText`, headers and body.

@@ -498,0 +559,0 @@ - The [`timeout` attribute](#the-timeout-attribute-and-request-timeouts) (can be disabled).

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc