Update checked-in dependencies

This commit is contained in:
github-actions[bot] 2021-07-27 22:26:09 +00:00
parent 3ba511a8f1
commit 1c4c64199f
175 changed files with 13227 additions and 15136 deletions

View file

@ -1,97 +0,0 @@
version: 2.1
references:
x-workdir: &work-dir
working_directory: ~/source
x-save-workspace: &persist-step
persist_to_workspace:
root: ~/source
paths:
- .
x-attach: &attach-step
attach_workspace:
at: .
jobs:
install-dependencies:
<<: *work-dir
docker:
- image: circleci/node:10
environment:
HUSKY_SKIP_INSTALL: 1
steps:
- checkout
- restore_cache:
keys:
- v1-npm-{{ checksum "package-lock.json" }}
- run:
name: Install dependencies
command: |
if [ ! -d node_modules ]; then
npm ci
fi
- save_cache:
key: v1-npm-{{ checksum "package-lock.json" }}
paths:
- node_modules
- *persist-step
lint:
<<: *work-dir
docker:
- image: node
steps:
- *attach-step
- run:
name: lint
command: npm run lint
node-8:
docker:
- image: circleci/node:8
steps:
- *attach-step
- run:
name: Test
command: npm test
node-10:
docker:
- image: circleci/node:10
steps:
- *attach-step
- run:
name: Test
command: npm test
node-12:
docker:
- image: circleci/node:12
steps:
- *attach-step
- run:
name: Test with coverage
command: npm run test-check-coverage
- run:
name: Upload coverage report
command: bash <(curl -s https://codecov.io/bash) -F unit -s coverage/lcov.info
workflows:
version: 2
commons-circle-ci:
jobs:
- install-dependencies
- lint:
requires:
- install-dependencies
- node-8:
requires:
- install-dependencies
- node-10:
requires:
- install-dependencies
- node-12:
requires:
- install-dependencies

View file

@ -1,21 +0,0 @@
; EditorConfig file: http://EditorConfig.org
; Install the "EditorConfig" plugin into your editor to use
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 4
trim_trailing_whitespace = true
# Matches the exact files either package.json or .travis.yml
[{package.json, .travis.yml}]
indent_style = space
indent_size = 2
; Needed if doing `git add --patch` to edit patches
[*.diff]
trim_trailing_whitespace = false

View file

@ -1 +0,0 @@
coverage/*

View file

@ -1,52 +0,0 @@
extends:
- sinon
- 'plugin:prettier/recommended'
env:
browser: true
node: true
globals:
ArrayBuffer: false
Map: false
Promise: false
Set: false
Symbol: false
plugins:
- ie11
- local-rules
rules:
strict: [error, 'global']
# authors are expected to understand function hoisting
no-use-before-define: off
ie11/no-collection-args: error
ie11/no-for-in-const: error
ie11/no-loop-func: warn
ie11/no-weak-collections: error
local-rules/no-prototype-methods: error
overrides:
- files: '*.test.*'
plugins:
- mocha
env:
mocha: true
rules:
max-nested-callbacks:
- warn
- 6
mocha/handle-done-callback: error
mocha/no-exclusive-tests: error
mocha/no-global-tests: error
mocha/no-hooks-for-single-case: off
mocha/no-identical-title: error
mocha/no-mocha-arrows: error
mocha/no-nested-tests: error
mocha/no-return-and-callback: error
mocha/no-sibling-hooks: error
mocha/no-skipped-tests: error
mocha/no-top-level-hooks: error
local-rules/no-prototype-methods: off

View file

@ -1,3 +0,0 @@
{
"tabWidth": 4
}

View file

@ -1,5 +1,37 @@
# Changes
## 1.8.3
- [`6af2d0c`](https://github.com/sinonjs/commons/commit/6af2d0cf33e9fd1e4aaef5308fd16a9cd78a5782)
Bump y18n from 4.0.0 to 4.0.1 (dependabot[bot])
>
> Bumps [y18n](https://github.com/yargs/y18n) from 4.0.0 to 4.0.1.
> - [Release notes](https://github.com/yargs/y18n/releases)
> - [Changelog](https://github.com/yargs/y18n/blob/master/CHANGELOG.md)
> - [Commits](https://github.com/yargs/y18n/commits)
>
> Signed-off-by: dependabot[bot] <support@github.com>
_Released on 2021-04-08._
## 1.8.2
- [`6b7a796`](https://github.com/sinonjs/commons/commit/6b7a796ffc088b43dc283cc4477a7d641720dc96)
Add .d.ts files to package (Morgan Roderick)
>
> In order to improve the experience of TypeScript users, we are compiling
> `.d.ts` files from the JSDoc and distributing them with the package
>
_Released on 2021-01-13._
## 1.8.1
- [`07b9e7a`](https://github.com/sinonjs/commons/commit/07b9e7a1d784771273a9a58d74945bbc7319b5d4)
Optimize npm package size (Uladzimir Havenchyk)
_Released on 2020-07-17._
## 1.8.0
- [`4282205`](https://github.com/sinonjs/commons/commit/4282205343a4dcde2a35ccf2a8c2094300dad369)

View file

@ -1,84 +0,0 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
* Focusing on what is best not just for us as individuals, but for the overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement by e-mailing any or all of [Morgan Roderick](mailto:morgan@roderick.dk), [Max Antoni](mailto:mail@maxantoni.de), [Carl-Erik Kopseng](mailto:carlerik@gmail.com). All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series of actions.
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.

View file

@ -8,9 +8,9 @@ Simple functions shared among the sinon end user libraries
## Rules
* Follows the [Sinon.JS compatibility](https://github.com/sinonjs/sinon/blob/master/CONTRIBUTING.md#compatibility)
* 100% test coverage
* Code formatted using [Prettier](https://prettier.io)
* No side effects welcome! (only pure functions)
* No platform specific functions
* One export per file (any bundler can do tree shaking)
- Follows the [Sinon.JS compatibility](https://github.com/sinonjs/sinon/blob/master/CONTRIBUTING.md#compatibility)
- 100% test coverage
- Code formatted using [Prettier](https://prettier.io)
- No side effects welcome! (only pure functions)
- No platform specific functions
- One export per file (any bundler can do tree shaking)

View file

@ -1,81 +0,0 @@
/* eslint-disable jsdoc/require-jsdoc, jsdoc/no-undefined-types */
"use strict";
function getPrototypeMethods(prototype) {
/* eslint-disable local-rules/no-prototype-methods */
return Object.getOwnPropertyNames(prototype).filter(function(name) {
return (
typeof prototype[name] === "function" &&
prototype.hasOwnProperty(name)
);
});
}
var DISALLOWED_ARRAY_PROPS = getPrototypeMethods(Array.prototype);
var DISALLOWED_OBJECT_PROPS = getPrototypeMethods(Object.prototype);
module.exports = {
// rule to disallow direct use of prototype methods of builtins
"no-prototype-methods": {
meta: {
docs: {
description: "disallow calling prototype methods directly",
category: "Possible Errors",
recommended: false,
url: "https://eslint.org/docs/rules/no-prototype-builtins"
},
schema: []
},
create: function(context) {
/**
* Reports if a disallowed property is used in a CallExpression
*
* @param {ASTNode} node The CallExpression node.
* @returns {void}
*/
function disallowBuiltIns(node) {
if (
node.callee.type !== "MemberExpression" ||
node.callee.computed ||
// allow static method calls
node.callee.object.name === "Array" ||
node.callee.object.name === "Object"
) {
return;
}
var propName = node.callee.property.name;
if (DISALLOWED_OBJECT_PROPS.indexOf(propName) > -1) {
context.report({
message:
"Do not access {{obj}} prototype method '{{prop}}' from target object.",
loc: node.callee.property.loc.start,
data: {
obj: "Object",
prop: propName
},
node: node
});
} else if (DISALLOWED_ARRAY_PROPS.indexOf(propName) > -1) {
context.report({
message:
"Do not access {{obj}} prototype method '{{prop}}' from target object.",
loc: node.callee.property.loc.start,
data: {
obj: "Array",
prop: propName
},
node: node
});
}
}
return {
CallExpression: disallowBuiltIns
};
}
}
};

View file

@ -12,7 +12,7 @@ module.exports = function every(obj, fn) {
var pass = true;
try {
/* eslint-disable-next-line local-rules/no-prototype-methods */
// eslint-disable-next-line @sinonjs/no-prototype-methods/no-prototype-methods
obj.forEach(function() {
if (!fn.apply(this, arguments)) {
// Throwing an error is the only way to break `forEach`

View file

@ -22,7 +22,6 @@ console.log(answer);
// => 2
```
## With cached references
```js

View file

@ -3,7 +3,7 @@
var call = Function.call;
module.exports = function copyPrototypeMethods(prototype) {
/* eslint-disable local-rules/no-prototype-methods */
// eslint-disable-next-line @sinonjs/no-prototype-methods/no-prototype-methods
return Object.getOwnPropertyNames(prototype).reduce(function(result, name) {
// ignore size because it throws from Map
if (

View file

@ -8,7 +8,7 @@
*/
function valueToString(value) {
if (value && value.toString) {
/* eslint-disable-next-line local-rules/no-prototype-methods */
// eslint-disable-next-line @sinonjs/no-prototype-methods/no-prototype-methods
return value.toString();
}
return String(value);

View file

@ -1,14 +1,19 @@
{
"name": "@sinonjs/commons",
"version": "1.8.0",
"version": "1.8.3",
"description": "Simple functions shared among the sinon end user libraries",
"main": "lib/index.js",
"types": "./types/index.d.ts",
"scripts": {
"build": "rm -rf types && tsc",
"lint": "eslint .",
"precommit": "lint-staged",
"test": "mocha --recursive -R dot \"lib/**/*.test.js\"",
"test-check-coverage": "npm run test-coverage && nyc check-coverage --branches 100 --functions 100 --lines 100",
"test-coverage": "nyc --reporter text --reporter html --reporter lcovonly npm run test",
"prepublishOnly": "npm run build",
"prettier:check": "prettier --check '**/*.{js,css,md}'",
"prettier:write": "prettier --write '**/*.{js,css,md}'",
"preversion": "npm run test-check-coverage",
"version": "changes --commits --footer",
"postversion": "git push --follow-tags && npm publish"
@ -17,6 +22,10 @@
"type": "git",
"url": "git+https://github.com/sinonjs/commons.git"
},
"files": [
"lib",
"types"
],
"author": "",
"license": "BSD-3-Clause",
"bugs": {
@ -24,11 +33,11 @@
},
"homepage": "https://github.com/sinonjs/commons#readme",
"lint-staged": {
"*.js": [
"eslint"
]
"*.{js,css,md}": "prettier --check",
"*.js": "eslint"
},
"devDependencies": {
"@sinonjs/eslint-plugin-no-prototype-methods": "^0.1.0",
"@sinonjs/referee-sinon": "7.0.2",
"@studio/changes": "^2.0.0",
"eslint": "^6.1.0",
@ -36,7 +45,6 @@
"eslint-config-sinon": "^4.0.0",
"eslint-plugin-ie11": "^1.0.0",
"eslint-plugin-jsdoc": "^22.1.0",
"eslint-plugin-local-rules": "^0.1.0",
"eslint-plugin-mocha": "^6.1.1",
"eslint-plugin-prettier": "^3.0.0",
"husky": "4.2.3",
@ -45,9 +53,15 @@
"lint-staged": "10.1.1",
"mocha": "7.1.0",
"nyc": "15.0.0",
"prettier": "^1.14.3"
"prettier": "^1.14.3",
"typescript": "^4.1.3"
},
"dependencies": {
"type-detect": "4.0.8"
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
}
}

View file

@ -0,0 +1,36 @@
export = calledInOrder;
/**
* A Sinon proxy object (fake, spy, stub)
*
* @typedef {object} SinonProxy
* @property {Function} calledBefore - A method that determines if this proxy was called before another one
* @property {string} id - Some id
* @property {number} callCount - Number of times this proxy has been called
*/
/**
* Returns true when the spies have been called in the order they were supplied in
*
* @param {SinonProxy[] | SinonProxy} spies An array of proxies, or several proxies as arguments
* @returns {boolean} true when spies are called in order, false otherwise
*/
declare function calledInOrder(spies: SinonProxy[] | SinonProxy, ...args: any[]): boolean;
declare namespace calledInOrder {
export { SinonProxy };
}
/**
* A Sinon proxy object (fake, spy, stub)
*/
type SinonProxy = {
/**
* - A method that determines if this proxy was called before another one
*/
calledBefore: Function;
/**
* - Some id
*/
id: string;
/**
* - Number of times this proxy has been called
*/
callCount: number;
};

8
node_modules/@sinonjs/commons/types/class-name.d.ts generated vendored Normal file
View file

@ -0,0 +1,8 @@
export = className;
/**
* Returns a display name for a value from a constructor
*
* @param {object} value A value to examine
* @returns {(string|null)} A string or null
*/
declare function className(value: object): (string | null);

3
node_modules/@sinonjs/commons/types/deprecated.d.ts generated vendored Normal file
View file

@ -0,0 +1,3 @@
export function wrap(func: Function, msg: string): Function;
export function defaultMsg(packageName: string, funcName: string): string;
export function printWarning(msg: string): undefined;

2
node_modules/@sinonjs/commons/types/every.d.ts generated vendored Normal file
View file

@ -0,0 +1,2 @@
declare function _exports(obj: object, fn: Function): boolean;
export = _exports;

View file

@ -0,0 +1,2 @@
declare function _exports(func: Function): string;
export = _exports;

7
node_modules/@sinonjs/commons/types/global.d.ts generated vendored Normal file
View file

@ -0,0 +1,7 @@
export = globalObject;
/**
* A reference to the global object
*
* @type {object} globalObject
*/
declare var globalObject: object;

17
node_modules/@sinonjs/commons/types/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,17 @@
export const global: any;
export const calledInOrder: typeof import("./called-in-order");
export const className: typeof import("./class-name");
export const deprecated: typeof import("./deprecated");
export const every: (obj: any, fn: Function) => boolean;
export const functionName: (func: Function) => string;
export const orderByFirstCall: typeof import("./order-by-first-call");
export const prototypes: {
array: any;
function: any;
map: any;
object: any;
set: any;
string: any;
};
export const typeOf: (value: any) => string;
export const valueToString: typeof import("./value-to-string");

View file

@ -0,0 +1,26 @@
export = orderByFirstCall;
/**
* A Sinon proxy object (fake, spy, stub)
*
* @typedef {object} SinonProxy
* @property {Function} getCall - A method that can return the first call
*/
/**
* Sorts an array of SinonProxy instances (fake, spy, stub) by their first call
*
* @param {SinonProxy[] | SinonProxy} spies
* @returns {SinonProxy[]}
*/
declare function orderByFirstCall(spies: SinonProxy[] | SinonProxy): SinonProxy[];
declare namespace orderByFirstCall {
export { SinonProxy };
}
/**
* A Sinon proxy object (fake, spy, stub)
*/
type SinonProxy = {
/**
* - A method that can return the first call
*/
getCall: Function;
};

View file

@ -0,0 +1,2 @@
declare const _exports: any;
export = _exports;

View file

@ -0,0 +1,2 @@
declare function _exports(prototype: any): any;
export = _exports;

View file

@ -0,0 +1,2 @@
declare const _exports: any;
export = _exports;

View file

@ -0,0 +1,7 @@
export declare const array: any;
declare const _function: any;
export { _function as function };
export declare const map: any;
export declare const object: any;
export declare const set: any;
export declare const string: any;

View file

@ -0,0 +1,2 @@
declare const _exports: any;
export = _exports;

View file

@ -0,0 +1,2 @@
declare const _exports: any;
export = _exports;

View file

@ -0,0 +1,2 @@
declare const _exports: any;
export = _exports;

View file

@ -0,0 +1,2 @@
declare const _exports: any;
export = _exports;

2
node_modules/@sinonjs/commons/types/type-of.d.ts generated vendored Normal file
View file

@ -0,0 +1,2 @@
declare function _exports(value: any): string;
export = _exports;

View file

@ -0,0 +1,8 @@
export = valueToString;
/**
* Returns a string representation of the value
*
* @param {*} value
* @returns {string}
*/
declare function valueToString(value: any): string;

View file

@ -1,4 +1,79 @@
7.1.2 / 2021-05-28
==================
* Fix #382 by making config fields optional (#383)
* Fix #347 : Support util.promisify
7.1.1 / 2021-05-27
==================
* Fix JSDoc for createClock
7.1.0 / 2021-05-20
==================
* Remove Safari from Sauce Lab (ref #380)
* Bump hosted-git-info from 2.6.0 to 2.8.9
* Bump handlebars from 4.7.6 to 4.7.7
* Bump lodash from 4.17.19 to 4.17.21
* Add in latest Safari and evergreen Edge
* Drop IE11 and Safari 9
* chore: add type tests (#373)
* remove constructor types
* use globalThis to avoid conflicts
* Update yargs-parser
* Update mkdirp
* Upgrade jsdom
* Upgrade mochify to latest
* Upgrade Mocha to latest
* Bump y18n from 4.0.0 to 4.0.1
* make config optional
* add a bunch more types
7.0.5 / 2021-04-11
==================
* Fix up some clock types in JSDoc (becomes `.d.ts`) (#370)
* Fix refresh arguments forwarding (#369)
7.0.4 / 2021-04-08
==================
* Fix usage with TypeScript
7.0.3 / 2021-03-02
==================
* Removing the use of eval in Node.js (#331)
* Drop Node 8
* Add docs about typings (#357)
7.0.2 / 2021-01-18
==================
* Make config options optional in TypeScript defs (#354)
7.0.1 / 2021-01-14
==================
* Update README section about browser use
7.0.0 / 2021-01-12
==================
* Remove bundle from package. If you're loading `fake-timers` via
script tag, you'll now have to provide your own bundled version
* Add .d.ts files to package
* Revert "Add stack trace to code recursively scheduling timers" (#338)
* Remove unnecessary durations and use globals
* Support timeout.refresh in node environments
* Fix #319: Error message changed to TypeError
* Fix #319: The use of 'eval' has been removed
* Fix #304: clearTimeout clears setInterval and clearInterval clears setTimeout
* Remove config.target (#318)
6.0.1 / 2020-03-24
==================

View file

@ -14,6 +14,28 @@ wait.
`@sinonjs/fake-timers` is extracted from [Sinon.JS](https://github.com/sinonjs/sinon.js) and targets the [same runtimes](https://sinonjs.org/releases/latest/#supported-runtimes).
## Help us get our TypeScript definitions production ready!
In version 7 we introduced TypeScript definitions that are generated from our JSDoc. This makes importing types from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/sinonjs__fake-timers/index.d.ts) superfluous, but we have just gotten started and we need your work for this to be up to the same quality. Until that happens typings from DefinitelyTyped still can be used:
```sh
npm install -D @types/sinonjs__fake-timers
```
Add this to tsconfig.json
```
{
"compilerOptions": {
...
"paths": {
...
"@sinonjs/fake-timers": ["node_modules/@types/sinonjs__fake-timers"]
}
}
}
```
## Installation
`@sinonjs/fake-timers` can be used in both Node and browser environments. Installation is as easy as
@ -22,11 +44,7 @@ wait.
npm install @sinonjs/fake-timers
```
If you want to use `@sinonjs/fake-timers` in a browser you can use [the pre-built
version](https://github.com/sinonjs/fake-timers/blob/master/fake-timers.js) available in the repo
and the npm package. Using npm you only need to reference `./node_modules/@sinonjs/fake-timers/fake-timers.js` in your `<script>` tags.
You are always free to [build it yourself](https://github.com/sinonjs/fake-timers/blob/53ea4d9b9e5bcff53cc7c9755dc9aa340368cf1c/package.json#L22), of course.
If you want to use `@sinonjs/fake-timers` in a browser you can either build your own bundle or use [Skypack](https://www.skypack.dev).
## Usage
@ -39,7 +57,9 @@ var FakeTimers = require("@sinonjs/fake-timers");
var clock = FakeTimers.createClock();
clock.setTimeout(function () {
console.log("The poblano is a mild chili pepper originating in the state of Puebla, Mexico.");
console.log(
"The poblano is a mild chili pepper originating in the state of Puebla, Mexico."
);
}, 15);
// ...
@ -48,7 +68,7 @@ clock.tick(15);
```
Upon executing the last line, an interesting fact about the
[Poblano](http://en.wikipedia.org/wiki/Poblano) will be printed synchronously to
[Poblano](https://en.wikipedia.org/wiki/Poblano) will be printed synchronously to
the screen. If you want to simulate asynchronous behavior, you have to use your
imagination when calling the various functions.
@ -83,9 +103,9 @@ To hijack timers in another context pass it to the `install` method.
```js
var FakeTimers = require("@sinonjs/fake-timers");
var context = {
setTimeout: setTimeout // By default context.setTimeout uses the global setTimeout
}
var clock = FakeTimers.install({target: context});
setTimeout: setTimeout, // By default context.setTimeout uses the global setTimeout
};
var clock = FakeTimers.withGlobal(context).install();
context.setTimeout(fn, 15); // Schedules with clock.setTimeout
@ -97,9 +117,10 @@ Usually you want to install the timers onto the global object, so call `install`
without arguments.
#### Automatically incrementing mocked time
Since version 2.0 FakeTimers supports the possibility to attach the faked timers
to any change in the real system time. This basically means you no longer need
to `tick()` the clock in a situation where you won't know **when** to call `tick()`.
FakeTimers supports the possibility to attach the faked timers to any change
in the real system time. This means that there is no need to `tick()` the
clock in a situation where you won't know **when** to call `tick()`.
Please note that this is achieved using the original setImmediate() API at a certain
configurable interval `config.advanceTimeDelta` (default: 20ms). Meaning time would
@ -109,18 +130,21 @@ An example would be:
```js
var FakeTimers = require("@sinonjs/fake-timers");
var clock = FakeTimers.install({shouldAdvanceTime: true, advanceTimeDelta: 40});
setTimeout(() => {
console.log('this just timed out'); //executed after 40ms
}, 30);
setImmediate(() => {
console.log('not so immediate'); //executed after 40ms
var clock = FakeTimers.install({
shouldAdvanceTime: true,
advanceTimeDelta: 40,
});
setTimeout(() => {
console.log('this timed out after'); //executed after 80ms
console.log("this just timed out"); //executed after 40ms
}, 30);
setImmediate(() => {
console.log("not so immediate"); //executed after 40ms
});
setTimeout(() => {
console.log("this timed out after"); //executed after 80ms
clock.uninstall();
}, 50);
```
@ -137,16 +161,16 @@ The `now` argument may be a number (in milliseconds) or a Date object.
The `loopLimit` argument sets the maximum number of timers that will be run when calling `runAll()` before assuming that we have an infinite loop and throwing an error. The default is `1000`.
### `var clock = FakeTimers.install([config])`
Installs FakeTimers using the specified config (otherwise with epoch `0` on the global scope). The following configuration options are available
Parameter | Type | Default | Description
--------- | ---- | ------- | ------------
`config.target`| Object | global | installs FakeTimers onto the specified target context
`config.now` | Number/Date | 0 | installs FakeTimers with the specified unix epoch
`config.toFake` | String[] | ["setTimeout", "clearTimeout", "setImmediate", "clearImmediate","setInterval", "clearInterval", "Date", "requestAnimationFrame", "cancelAnimationFrame", "requestIdleCallback", "cancelIdleCallback", "hrtime"] | an array with explicit function names to hijack. *When not set, FakeTimers will automatically fake all methods **except** `nextTick`* e.g., `FakeTimers.install({ toFake: ["setTimeout","nextTick"]})` will fake only `setTimeout` and `nextTick`
`config.loopLimit` | Number | 1000 | the maximum number of timers that will be run when calling runAll()
`config.shouldAdvanceTime` | Boolean | false | tells FakeTimers to increment mocked time automatically based on the real system time shift (e.g. the mocked time will be incremented by 20ms for every 20ms change in the real system time)
`config.advanceTimeDelta` | Number | 20 | relevant only when using with `shouldAdvanceTime: true`. increment mocked time by `advanceTimeDelta` ms every `advanceTimeDelta` ms change in the real system time.
| Parameter | Type | Default | Description |
| -------------------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `config.now` | Number/Date | 0 | installs FakeTimers with the specified unix epoch |
| `config.toFake` | String[] | ["setTimeout", "clearTimeout", "setImmediate", "clearImmediate","setInterval", "clearInterval", "Date", "requestAnimationFrame", "cancelAnimationFrame", "requestIdleCallback", "cancelIdleCallback", "hrtime"] | an array with explicit function names to hijack. _When not set, FakeTimers will automatically fake all methods **except** `nextTick`_ e.g., `FakeTimers.install({ toFake: ["setTimeout","nextTick"]})` will fake only `setTimeout` and `nextTick` |
| `config.loopLimit` | Number | 1000 | the maximum number of timers that will be run when calling runAll() |
| `config.shouldAdvanceTime` | Boolean | false | tells FakeTimers to increment mocked time automatically based on the real system time shift (e.g. the mocked time will be incremented by 20ms for every 20ms change in the real system time) |
| `config.advanceTimeDelta` | Number | 20 | relevant only when using with `shouldAdvanceTime: true`. increment mocked time by `advanceTimeDelta` ms every `advanceTimeDelta` ms change in the real system time. |
### `var id = clock.setTimeout(callback, timeout)`
@ -218,6 +242,7 @@ Returns the number of waiting timers. This can be used to assert that a test
finishes without leaking any timers.
### `clock.hrtime(prevTime?)`
Only available in Node.js, mimicks process.hrtime().
### `clock.nextTick(callback)`
@ -225,8 +250,8 @@ Only available in Node.js, mimicks process.hrtime().
Only available in Node.js, mimics `process.nextTick` to enable completely synchronous testing flows.
### `clock.performance.now()`
Only available in browser environments, mimicks performance.now().
Only available in browser environments, mimicks performance.now().
### `clock.tick(time)` / `await clock.tickAsync(time)`
@ -294,8 +319,8 @@ setSystemTime().
### `clock.uninstall()`
Restores the original methods on the `target` that was passed to
`FakeTimers.install`, or the native timers if no `target` was given.
Restores the original methods of the native timers or the methods on the object
that was passed to `FakeTimers.withGlobal`
### `Date`
@ -338,4 +363,4 @@ npm test-headless
## License
BSD 3-clause "New" or "Revised" License (see LICENSE file)
BSD 3-clause "New" or "Revised" License (see LICENSE file)

File diff suppressed because it is too large Load diff

View file

@ -1,42 +1,45 @@
{
"name": "@sinonjs/fake-timers",
"description": "Fake JavaScript timers",
"version": "6.0.1",
"homepage": "http://github.com/sinonjs/fake-timers",
"version": "7.1.2",
"homepage": "https://github.com/sinonjs/fake-timers",
"author": "Christian Johansen",
"repository": {
"type": "git",
"url": "http://github.com/sinonjs/fake-timers.git"
"url": "https://github.com/sinonjs/fake-timers.git"
},
"bugs": {
"mail": "christian@cjohansen.no",
"url": "http://github.com/sinonjs/fake-timers/issues"
"url": "https://github.com/sinonjs/fake-timers/issues"
},
"license": "BSD-3-Clause",
"scripts": {
"build": "rm -rf types && tsc",
"lint": "eslint .",
"test-node": "mocha test/ integration-test/ -R dot --check-leaks",
"test-headless": "mochify --no-detect-globals --timeout=10000",
"test-check-coverage": "npm run test-coverage && nyc check-coverage",
"test-cloud": "mochify --wd --no-detect-globals --timeout=10000",
"test-coverage": "nyc --all --reporter text --reporter html --reporter lcovonly npm run test-node",
"test": "npm run lint && npm run test-node && npm run test-headless",
"bundle": "browserify --no-detect-globals -s FakeTimers -o fake-timers.js src/fake-timers-src.js",
"prepublishOnly": "npm run bundle",
"test-types": "tsd && tsc --noEmit test/check-types.ts",
"test": "npm run test-node && npm run test-headless",
"prettier:check": "prettier --check '**/*.{js,css,md,ts}'",
"prettier:write": "prettier --write '**/*.{js,css,md,ts}'",
"prepublishOnly": "npm run build",
"preversion": "./scripts/preversion.sh",
"version": "./scripts/version.sh",
"postversion": "./scripts/postversion.sh"
},
"lint-staged": {
"*.{js,css,md}": "prettier --check",
"*.js": "eslint"
},
"files": [
"src/",
"fake-timers.js"
"types"
],
"devDependencies": {
"@sinonjs/referee-sinon": "6.0.1",
"browserify": "16.5.0",
"eslint": "6.8.0",
"eslint-config-prettier": "6.10.0",
"eslint-config-sinon": "3.0.1",
@ -44,42 +47,23 @@
"eslint-plugin-mocha": "6.2.2",
"eslint-plugin-prettier": "3.1.1",
"husky": "4.2.1",
"jsdom": "15.1.1",
"jsdom": "16.5.2",
"lint-staged": "10.0.7",
"mocha": "7.0.1",
"mochify": "6.6.0",
"npm-run-all": "4.1.5",
"mocha": "8.3.2",
"mochify": "7.0.0",
"nyc": "14.1.1",
"prettier": "1.19.1"
"prettier": "2.2.1",
"tsd": "0.14.0",
"typescript": "4.1.3"
},
"eslintConfig": {
"extends": "eslint-config-sinon",
"plugins": [
"ie11"
],
"rules": {
"ie11/no-collection-args": [
"error"
],
"ie11/no-for-in-const": [
"error"
],
"ie11/no-loop-func": [
"warn"
],
"ie11/no-weak-collections": [
"error"
]
}
},
"module": "./fake-timers.js",
"main": "./src/fake-timers-src.js",
"types": "./types/fake-timers-src.d.ts",
"dependencies": {
"@sinonjs/commons": "^1.7.0"
},
"husky": {
"hooks": {
"pre-commit": "run-p lint test-node"
"pre-commit": "npm run lint"
}
},
"nyc": {
@ -90,7 +74,11 @@
"exclude": [
"**/*-test.js",
"coverage/**",
"types/**",
"fake-timers.js"
]
},
"tsd": {
"directory": "test"
}
}

View file

@ -2,15 +2,76 @@
var globalObject = require("@sinonjs/commons").global;
// eslint-disable-next-line complexity
/**
* @typedef {object} Clock
* @property {number} now
* @property {any} timeouts
* @property {typeof globalThis.Date} Date
* @property {number} loopLimit
* @property {(func: Function, timeout: number) => number} requestIdleCallback
* @property {(timerId: number) => void} cancelIdleCallback
* @property {setTimeout} setTimeout
* @property {clearTimeout} clearTimeout
* @property {(func: Function, ...args: any[]) => void} nextTick
* @property {queueMicrotask} queueMicrotask
* @property {setInterval} setInterval
* @property {clearInterval} clearInterval
* @property {(func: (...args: any[]) => void, ...args: any[]) => NodeTimer} setImmediate
* @property {(timerId: NodeTimer) => void} clearImmediate
* @property {() => number} countTimers
* @property {(func: (timer: number) => void) => number} requestAnimationFrame
* @property {(timerId: number) => void} cancelAnimationFrame
* @property {() => void} runMicrotasks
* @property {(tickValue: string | number) => number} tick
* @property {(tickValue: string | number) => Promise<number>} tickAsync
* @property {() => number} next
* @property {() => Promise<number>} nextAsync
* @property {() => number} runAll
* @property {() => number} runToFrame
* @property {() => Promise<number>} runAllAsync
* @property {() => number} runToLast
* @property {() => Promise<number>} runToLastAsync
* @property {() => void} reset
* @property {(systemTime: number | Date) => void} setSystemTime
* @property {({now(): number})} performance
* @property {(prev: any) => number[]} hrTime
* @property {() => void} uninstall Uninstall the clock.
* @property {any} methods
*/
/**
* Configuration object for the `install` method.
*
* @typedef {object} Config
* @property {number|Date} [now] a number (in milliseconds) or a Date object (default epoch)
* @property {string[]} [toFake] names of the methods that should be faked.
* @property {number} [loopLimit] the maximum number of timers that will be run when calling runAll()
* @property {boolean} [shouldAdvanceTime] tells FakeTimers to increment mocked time automatically (default false)
* @property {number} [advanceTimeDelta] increment mocked time every <<advanceTimeDelta>> ms (default: 20ms)
*/
/**
* @typedef {object} NodeTimer
* @property {() => boolean} hasRef
* @property {() => any} ref
* @property {() => any} unref
*/
/* eslint-disable complexity */
/**
* Mocks available features in the specified global namespace.
*
* @param {*} _global Namespace to mock (e.g. `window`)
*/
function withGlobal(_global) {
var userAgent = _global.navigator && _global.navigator.userAgent;
var isRunningInIE = userAgent && userAgent.indexOf("MSIE ") > -1;
var maxTimeout = Math.pow(2, 31) - 1; //see https://heycam.github.io/webidl/#abstract-opdef-converttoint
var NOOP = function() {
var NOOP = function () {
return undefined;
};
var NOOP_ARRAY = function() {
var NOOP_ARRAY = function () {
return [];
};
var timeoutResult = _global.setTimeout(NOOP, 0);
@ -44,7 +105,7 @@ function withGlobal(_global) {
_global.setImmediate && typeof _global.setImmediate === "function";
// Make properties writable in IE, as per
// http://www.adequatelygood.com/Replacing-setTimeout-Globally.html
// https://www.adequatelygood.com/Replacing-setTimeout-Globally.html
/* eslint-disable no-self-assign */
if (isRunningInIE) {
_global.setTimeout = _global.setTimeout;
@ -72,10 +133,6 @@ function withGlobal(_global) {
return Number.isFinite(num);
}
if (typeof num !== "number") {
return false;
}
return isFinite(num);
}
@ -117,8 +174,8 @@ function withGlobal(_global) {
/**
* Get the decimal part of the millisecond value as nanoseconds
*
* @param {Number} msFloat the number of milliseconds
* @returns {Number} an integer number of nanoseconds in the range [0,1e6)
* @param {number} msFloat the number of milliseconds
* @returns {number} an integer number of nanoseconds in the range [0,1e6)
*
* Example: nanoRemainer(123.456789) -> 456789
*/
@ -132,7 +189,7 @@ function withGlobal(_global) {
/**
* Used to grok the `now` parameter to createClock.
* @param epoch {Date|number} the system time
* @param {Date|number} epoch the system time
*/
function getEpoch(epoch) {
if (!epoch) {
@ -271,9 +328,25 @@ function withGlobal(_global) {
throw new Error("Callback must be provided to timer calls");
}
if (addTimerReturnsObject) {
// Node.js environment
if (typeof timer.func !== "function") {
throw new TypeError(
"[ERR_INVALID_CALLBACK]: Callback must be a function. Received " +
timer.func +
" of type " +
typeof timer.func
);
}
}
timer.type = timer.immediate ? "Immediate" : "Timeout";
if (timer.hasOwnProperty("delay")) {
if (typeof timer.delay !== "number") {
timer.delay = parseInt(timer.delay, 10);
}
if (!isNumberFinite(timer.delay)) {
timer.delay = 0;
}
@ -305,15 +378,17 @@ function withGlobal(_global) {
if (addTimerReturnsObject) {
var res = {
id: timer.id,
ref: function() {
ref: function () {
return res;
},
unref: function() {
unref: function () {
return res;
},
refresh: function() {
return res;
}
refresh: function () {
clearTimeout(timer.id);
var args = [timer.func, timer.delay].concat(timer.args);
return setTimeout.apply(null, args);
},
};
return res;
}
@ -422,7 +497,10 @@ function withGlobal(_global) {
timer.func.apply(null, timer.args);
} else {
/* eslint no-eval: "off" */
eval(timer.func);
var eval2 = eval;
(function () {
eval2(timer.func);
})();
}
}
@ -444,7 +522,11 @@ function withGlobal(_global) {
if (clock.timers.hasOwnProperty(id)) {
// check that the ID matches a timer of the correct type
var timer = clock.timers[id];
if (timer.type === ttype) {
if (
timer.type === ttype ||
(timer.type === "Timeout" && ttype === "Interval") ||
(timer.type === "Interval" && ttype === "Timeout")
) {
delete clock.timers[id];
} else {
var clear =
@ -466,17 +548,17 @@ function withGlobal(_global) {
}
}
function uninstall(clock, target, config) {
function uninstall(clock, config) {
var method, i, l;
var installedHrTime = "_hrtime";
var installedNextTick = "_nextTick";
for (i = 0, l = clock.methods.length; i < l; i++) {
method = clock.methods[i];
if (method === "hrtime" && target.process) {
target.process.hrtime = clock[installedHrTime];
} else if (method === "nextTick" && target.process) {
target.process.nextTick = clock[installedNextTick];
if (method === "hrtime" && _global.process) {
_global.process.hrtime = clock[installedHrTime];
} else if (method === "nextTick" && _global.process) {
_global.process.nextTick = clock[installedNextTick];
} else if (method === "performance") {
var originalPerfDescriptor = Object.getOwnPropertyDescriptor(
clock,
@ -488,25 +570,25 @@ function withGlobal(_global) {
!originalPerfDescriptor.set
) {
Object.defineProperty(
target,
_global,
method,
originalPerfDescriptor
);
} else if (originalPerfDescriptor.configurable) {
target[method] = clock["_" + method];
_global[method] = clock["_" + method];
}
} else {
if (target[method] && target[method].hadOwnProperty) {
target[method] = clock["_" + method];
if (_global[method] && _global[method].hadOwnProperty) {
_global[method] = clock["_" + method];
if (
method === "clearInterval" &&
config.shouldAdvanceTime === true
) {
target[method](clock.attachedInterval);
_global[method](clock.attachedInterval);
}
} else {
try {
delete target[method];
delete _global[method];
} catch (ignore) {
/* eslint no-empty: "off" */
}
@ -527,7 +609,6 @@ function withGlobal(_global) {
}
function hijackMethod(target, method, clock) {
var prop;
clock[method].hadOwnProperty = Object.prototype.hasOwnProperty.call(
target,
method
@ -563,15 +644,14 @@ function withGlobal(_global) {
target[method] = clock[method];
}
} else {
target[method] = function() {
target[method] = function () {
return clock[method].apply(clock, arguments);
};
for (prop in clock[method]) {
if (clock[method].hasOwnProperty(prop)) {
target[method][prop] = clock[method][prop];
}
}
Object.defineProperties(
target[method],
Object.getOwnPropertyDescriptors(clock[method])
);
}
target[method].clock = clock;
@ -581,12 +661,32 @@ function withGlobal(_global) {
clock.tick(advanceTimeDelta);
}
/**
* @typedef {object} Timers
* @property {setTimeout} setTimeout
* @property {clearTimeout} clearTimeout
* @property {setInterval} setInterval
* @property {clearInterval} clearInterval
* @property {typeof globalThis.Date} Date
* @property {((fn: (...args: any[]) => void, ...args: any[]) => NodeTimer)=} setImmediate
* @property {((id: NodeTimer) => void)=} clearImmediate
* @property {((time?: [number, number]) => [number, number])=} hrtime
* @property {((fn: Function, ...args: any[]) => void)=} nextTick
* @property {({now(): number})=} performance
* @property {((fn: (timer: number) => void) => number)=} requestAnimationFrame
* @property {boolean=} queueMicrotask
* @property {((id: number) => void)=} cancelAnimationFrame
* @property {((fn: (deadline: any) => void, options?: any) => number)=} requestIdleCallback
* @property {((id: number) => void)=} cancelIdleCallback
*/
/** @type {Timers} */
var timers = {
setTimeout: _global.setTimeout,
clearTimeout: _global.clearTimeout,
setInterval: _global.setInterval,
clearInterval: _global.clearInterval,
Date: _global.Date
Date: _global.Date,
};
if (setImmediatePresent) {
@ -626,26 +726,12 @@ function withGlobal(_global) {
timers.cancelIdleCallback = _global.cancelIdleCallback;
}
var keys =
Object.keys ||
function(obj) {
var ks = [];
var key;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
ks.push(key);
}
}
return ks;
};
var originalSetTimeout = _global.setImmediate || _global.setTimeout;
/**
* @param start {Date|number} the system time - non-integer values are floored
* @param loopLimit {number} maximum number of timers that will be run when calling runAll()
* @param {Date|number} [start] the system time - non-integer values are floored
* @param {number} [loopLimit] maximum number of timers that will be run when calling runAll()
* @returns {Clock}
*/
function createClock(start, loopLimit) {
// eslint-disable-next-line no-param-reassign
@ -666,7 +752,7 @@ function withGlobal(_global) {
now: start,
timeouts: {},
Date: createDate(),
loopLimit: loopLimit
loopLimit: loopLimit,
};
clock.Date.clock = clock;
@ -705,7 +791,7 @@ function withGlobal(_global) {
}
if (hrtimeBigintPresent) {
hrtime.bigint = function() {
hrtime.bigint = function () {
var parts = hrtime();
return BigInt(parts[0]) * BigInt(1e9) + BigInt(parts[1]); // eslint-disable-line
};
@ -727,7 +813,7 @@ function withGlobal(_global) {
delay:
typeof timeout === "undefined"
? timeToNextIdlePeriod
: Math.min(timeout, timeToNextIdlePeriod)
: Math.min(timeout, timeToNextIdlePeriod),
});
return result.id || result;
@ -741,7 +827,7 @@ function withGlobal(_global) {
return addTimer(clock, {
func: func,
args: Array.prototype.slice.call(arguments, 2),
delay: timeout
delay: timeout,
});
};
if (typeof _global.Promise !== "undefined" && utilPromisify) {
@ -754,7 +840,7 @@ function withGlobal(_global) {
addTimer(clock, {
func: resolve,
args: [arg],
delay: timeout
delay: timeout,
});
});
};
@ -767,7 +853,7 @@ function withGlobal(_global) {
clock.nextTick = function nextTick(func) {
return enqueueJob(clock, {
func: func,
args: Array.prototype.slice.call(arguments, 1)
args: Array.prototype.slice.call(arguments, 1),
});
};
@ -782,7 +868,7 @@ function withGlobal(_global) {
func: func,
args: Array.prototype.slice.call(arguments, 2),
delay: timeout,
interval: timeout
interval: timeout,
});
};
@ -795,7 +881,7 @@ function withGlobal(_global) {
return addTimer(clock, {
func: func,
args: Array.prototype.slice.call(arguments, 1),
immediate: true
immediate: true,
});
};
@ -809,7 +895,7 @@ function withGlobal(_global) {
addTimer(clock, {
func: resolve,
args: [arg],
immediate: true
immediate: true,
});
});
};
@ -832,7 +918,7 @@ function withGlobal(_global) {
func: func,
delay: getTimeToNextFrame(),
args: [clock.now + getTimeToNextFrame()],
animation: true
animation: true,
});
return result.id || result;
@ -955,7 +1041,7 @@ function withGlobal(_global) {
nextPromiseTick =
isAsync &&
function() {
function () {
try {
compensationCheck();
postTimerCall();
@ -965,7 +1051,7 @@ function withGlobal(_global) {
}
};
compensationCheck = function() {
compensationCheck = function () {
// compensate for any setSystemTime() call during timer callback
if (oldNow !== clock.now) {
tickFrom += clock.now - oldNow;
@ -974,7 +1060,7 @@ function withGlobal(_global) {
}
};
postTimerCall = function() {
postTimerCall = function () {
timer = firstTimerInRange(clock, previous, tickTo);
previous = tickFrom;
};
@ -983,7 +1069,7 @@ function withGlobal(_global) {
}
/**
* @param {tickValue} {String|Number} number of milliseconds or a human-readable value like "01:11:15"
* @param {tickValue} {string|number} number of milliseconds or a human-readable value like "01:11:15"
*/
clock.tick = function tick(tickValue) {
return doTick(tickValue, false);
@ -991,8 +1077,8 @@ function withGlobal(_global) {
if (typeof _global.Promise !== "undefined") {
clock.tickAsync = function tickAsync(ms) {
return new _global.Promise(function(resolve, reject) {
originalSetTimeout(function() {
return new _global.Promise(function (resolve, reject) {
originalSetTimeout(function () {
try {
doTick(ms, true, resolve, reject);
} catch (e) {
@ -1023,8 +1109,8 @@ function withGlobal(_global) {
if (typeof _global.Promise !== "undefined") {
clock.nextAsync = function nextAsync() {
return new _global.Promise(function(resolve, reject) {
originalSetTimeout(function() {
return new _global.Promise(function (resolve, reject) {
originalSetTimeout(function () {
try {
var timer = firstTimer(clock);
if (!timer) {
@ -1042,7 +1128,7 @@ function withGlobal(_global) {
}
clock.duringTick = false;
originalSetTimeout(function() {
originalSetTimeout(function () {
if (err) {
reject(err);
} else {
@ -1065,7 +1151,7 @@ function withGlobal(_global) {
return clock.now;
}
numTimers = keys(clock.timers).length;
numTimers = Object.keys(clock.timers).length;
if (numTimers === 0) {
return clock.now;
}
@ -1086,10 +1172,10 @@ function withGlobal(_global) {
if (typeof _global.Promise !== "undefined") {
clock.runAllAsync = function runAllAsync() {
return new _global.Promise(function(resolve, reject) {
return new _global.Promise(function (resolve, reject) {
var i = 0;
function doRun() {
originalSetTimeout(function() {
originalSetTimeout(function () {
try {
var numTimers;
if (i < clock.loopLimit) {
@ -1142,8 +1228,8 @@ function withGlobal(_global) {
if (typeof _global.Promise !== "undefined") {
clock.runToLastAsync = function runToLastAsync() {
return new _global.Promise(function(resolve, reject) {
originalSetTimeout(function() {
return new _global.Promise(function (resolve, reject) {
originalSetTimeout(function () {
try {
var timer = lastTimer(clock);
if (!timer) {
@ -1194,7 +1280,7 @@ function withGlobal(_global) {
if (hasPerformancePrototype) {
var proto = _global.Performance.prototype;
Object.getOwnPropertyNames(proto).forEach(function(name) {
Object.getOwnPropertyNames(proto).forEach(function (name) {
if (name.indexOf("getEntries") === 0) {
// match expected return type for getEntries functions
clock.performance[name] = NOOP_ARRAY;
@ -1218,16 +1304,12 @@ function withGlobal(_global) {
return clock;
}
/* eslint-disable complexity */
/**
* @param config {Object} optional config
* @param config.target {Object} the target to install timers in (default `window`)
* @param config.now {number|Date} a number (in milliseconds) or a Date object (default epoch)
* @param config.toFake {string[]} names of the methods that should be faked.
* @param config.loopLimit {number} the maximum number of timers that will be run when calling runAll()
* @param config.shouldAdvanceTime {Boolean} tells FakeTimers to increment mocked time automatically (default false)
* @param config.advanceTimeDelta {Number} increment mocked time every <<advanceTimeDelta>> ms (default: 20ms)
* @param {Config=} [config] Optional config
* @returns {Clock}
*/
// eslint-disable-next-line complexity
function install(config) {
if (
arguments.length > 1 ||
@ -1247,19 +1329,24 @@ function withGlobal(_global) {
config.shouldAdvanceTime = config.shouldAdvanceTime || false;
config.advanceTimeDelta = config.advanceTimeDelta || 20;
if (config.target) {
throw new TypeError(
"config.target is no longer supported. Use `withGlobal(target)` instead."
);
}
var i, l;
var target = config.target || _global;
var clock = createClock(config.now, config.loopLimit);
clock.uninstall = function() {
return uninstall(clock, target, config);
clock.uninstall = function () {
return uninstall(clock, config);
};
clock.methods = config.toFake || [];
if (clock.methods.length === 0) {
// do not fake nextTick by default - GitHub#126
clock.methods = keys(timers).filter(function(key) {
clock.methods = Object.keys(timers).filter(function (key) {
return key !== "nextTick" && key !== "queueMicrotask";
});
}
@ -1267,17 +1354,17 @@ function withGlobal(_global) {
for (i = 0, l = clock.methods.length; i < l; i++) {
if (clock.methods[i] === "hrtime") {
if (
target.process &&
typeof target.process.hrtime === "function"
_global.process &&
typeof _global.process.hrtime === "function"
) {
hijackMethod(target.process, clock.methods[i], clock);
hijackMethod(_global.process, clock.methods[i], clock);
}
} else if (clock.methods[i] === "nextTick") {
if (
target.process &&
typeof target.process.nextTick === "function"
_global.process &&
typeof _global.process.nextTick === "function"
) {
hijackMethod(target.process, clock.methods[i], clock);
hijackMethod(_global.process, clock.methods[i], clock);
}
} else {
if (
@ -1289,27 +1376,31 @@ function withGlobal(_global) {
clock,
config.advanceTimeDelta
);
var intervalId = target[clock.methods[i]](
var intervalId = _global[clock.methods[i]](
intervalTick,
config.advanceTimeDelta
);
clock.attachedInterval = intervalId;
}
hijackMethod(target, clock.methods[i], clock);
hijackMethod(_global, clock.methods[i], clock);
}
}
return clock;
}
/* eslint-enable complexity */
return {
timers: timers,
createClock: createClock,
install: install,
withGlobal: withGlobal
withGlobal: withGlobal,
};
}
/* eslint-enable complexity */
var defaultImplementation = withGlobal(globalObject);
exports.timers = defaultImplementation.timers;

View file

@ -0,0 +1,187 @@
export type Clock = {
now: number;
timeouts: any;
Date: typeof globalThis.Date;
loopLimit: number;
requestIdleCallback: (func: Function, timeout: number) => number;
cancelIdleCallback: (timerId: number) => void;
setTimeout: typeof setTimeout;
clearTimeout: typeof clearTimeout;
nextTick: (func: Function, ...args: any[]) => void;
queueMicrotask: typeof queueMicrotask;
setInterval: typeof setInterval;
clearInterval: typeof clearInterval;
setImmediate: (func: (...args: any[]) => void, ...args: any[]) => NodeTimer;
clearImmediate: (timerId: NodeTimer) => void;
countTimers: () => number;
requestAnimationFrame: (func: (timer: number) => void) => number;
cancelAnimationFrame: (timerId: number) => void;
runMicrotasks: () => void;
tick: (tickValue: string | number) => number;
tickAsync: (tickValue: string | number) => Promise<number>;
next: () => number;
nextAsync: () => Promise<number>;
runAll: () => number;
runToFrame: () => number;
runAllAsync: () => Promise<number>;
runToLast: () => number;
runToLastAsync: () => Promise<number>;
reset: () => void;
setSystemTime: (systemTime: number | Date) => void;
performance: ({
now(): number;
});
hrTime: (prev: any) => number[];
/**
* Uninstall the clock.
*/
uninstall: () => void;
methods: any;
};
/**
* Configuration object for the `install` method.
*/
export type Config = {
/**
* a number (in milliseconds) or a Date object (default epoch)
*/
now?: number | Date;
/**
* names of the methods that should be faked.
*/
toFake?: string[];
/**
* the maximum number of timers that will be run when calling runAll()
*/
loopLimit?: number;
/**
* tells FakeTimers to increment mocked time automatically (default false)
*/
shouldAdvanceTime?: boolean;
/**
* increment mocked time every <<advanceTimeDelta>> ms (default: 20ms)
*/
advanceTimeDelta?: number;
};
export type NodeTimer = {
hasRef: () => boolean;
ref: () => any;
unref: () => any;
};
export namespace timers {
const setTimeout_1: typeof globalThis.setTimeout;
export { setTimeout_1 as setTimeout };
const clearTimeout_1: typeof globalThis.clearTimeout;
export { clearTimeout_1 as clearTimeout };
const setInterval_1: typeof globalThis.setInterval;
export { setInterval_1 as setInterval };
const clearInterval_1: typeof globalThis.clearInterval;
export { clearInterval_1 as clearInterval };
const Date_1: typeof globalThis.Date;
export { Date_1 as Date };
export const setImmediate: (fn: (...args: any[]) => void, ...args: any[]) => NodeTimer;
export const clearImmediate: (id: NodeTimer) => void;
export const hrtime: (time?: [number, number]) => [number, number];
export const nextTick: (fn: Function, ...args: any[]) => void;
export const performance: ({
now(): number;
}) | undefined;
export const requestAnimationFrame: (fn: (timer: number) => void) => number;
const queueMicrotask_1: boolean | undefined;
export { queueMicrotask_1 as queueMicrotask };
export const cancelAnimationFrame: (id: number) => void;
export const requestIdleCallback: (fn: (deadline: any) => void, options?: any) => number;
export const cancelIdleCallback: (id: number) => void;
}
/**
* @param {Date|number} [start] the system time - non-integer values are floored
* @param {number} [loopLimit] maximum number of timers that will be run when calling runAll()
* @returns {Clock}
*/
export function createClock(start?: Date | number, loopLimit?: number): Clock;
/**
* @param {Config=} [config] Optional config
* @returns {Clock}
*/
export function install(config?: Config | undefined, ...args: any[]): Clock;
/**
* @typedef {object} Clock
* @property {number} now
* @property {any} timeouts
* @property {typeof globalThis.Date} Date
* @property {number} loopLimit
* @property {(func: Function, timeout: number) => number} requestIdleCallback
* @property {(timerId: number) => void} cancelIdleCallback
* @property {setTimeout} setTimeout
* @property {clearTimeout} clearTimeout
* @property {(func: Function, ...args: any[]) => void} nextTick
* @property {queueMicrotask} queueMicrotask
* @property {setInterval} setInterval
* @property {clearInterval} clearInterval
* @property {(func: (...args: any[]) => void, ...args: any[]) => NodeTimer} setImmediate
* @property {(timerId: NodeTimer) => void} clearImmediate
* @property {() => number} countTimers
* @property {(func: (timer: number) => void) => number} requestAnimationFrame
* @property {(timerId: number) => void} cancelAnimationFrame
* @property {() => void} runMicrotasks
* @property {(tickValue: string | number) => number} tick
* @property {(tickValue: string | number) => Promise<number>} tickAsync
* @property {() => number} next
* @property {() => Promise<number>} nextAsync
* @property {() => number} runAll
* @property {() => number} runToFrame
* @property {() => Promise<number>} runAllAsync
* @property {() => number} runToLast
* @property {() => Promise<number>} runToLastAsync
* @property {() => void} reset
* @property {(systemTime: number | Date) => void} setSystemTime
* @property {({now(): number})} performance
* @property {(prev: any) => number[]} hrTime
* @property {() => void} uninstall Uninstall the clock.
* @property {any} methods
*/
/**
* Configuration object for the `install` method.
*
* @typedef {object} Config
* @property {number|Date} [now] a number (in milliseconds) or a Date object (default epoch)
* @property {string[]} [toFake] names of the methods that should be faked.
* @property {number} [loopLimit] the maximum number of timers that will be run when calling runAll()
* @property {boolean} [shouldAdvanceTime] tells FakeTimers to increment mocked time automatically (default false)
* @property {number} [advanceTimeDelta] increment mocked time every <<advanceTimeDelta>> ms (default: 20ms)
*/
/**
* @typedef {object} NodeTimer
* @property {() => boolean} hasRef
* @property {() => any} ref
* @property {() => any} unref
*/
/**
* Mocks available features in the specified global namespace.
*
* @param {*} _global Namespace to mock (e.g. `window`)
*/
export function withGlobal(_global: any): {
timers: {
setTimeout: typeof setTimeout;
clearTimeout: typeof clearTimeout;
setInterval: typeof setInterval;
clearInterval: typeof clearInterval;
Date: typeof globalThis.Date;
setImmediate?: (fn: (...args: any[]) => void, ...args: any[]) => NodeTimer;
clearImmediate?: (id: NodeTimer) => void;
hrtime?: (time?: [number, number]) => [number, number];
nextTick?: (fn: Function, ...args: any[]) => void;
performance?: ({
now(): number;
}) | undefined;
requestAnimationFrame?: (fn: (timer: number) => void) => number;
queueMicrotask?: boolean | undefined;
cancelAnimationFrame?: (id: number) => void;
requestIdleCallback?: (fn: (deadline: any) => void, options?: any) => number;
cancelIdleCallback?: (id: number) => void;
};
createClock: (start?: Date | number, loopLimit?: number) => Clock;
install: (config?: Config | undefined, ...args: any[]) => Clock;
withGlobal: typeof withGlobal;
};

View file

@ -1,43 +0,0 @@
# Changes
## 5.0.1
- [`47a360d`](https://github.com/sinonjs/formatio/commit/47a360d5c5db72ba8ced2d598421bfe105facc69)
Bump @sinonjs/samsam to latest (Morgan Roderick)
>
> This helps dedupe dependencies in Sinon. See https://github.com/sinonjs/sinon/issues/2224
>
_Released on 2020-02-20._
## 5.0.0
- [`116aedb`](https://github.com/sinonjs/formatio/commit/116aedb20ca89f5f022633457366afe17b070772)
Drop support for Node 8 (Morgan Roderick)
>
> As can be seen at https://github.com/nodejs/Release, Node 8 reached
> "end" of life on 2019-12-31, and is no longer actively supported.
>
> We will stop testing in Node 8 and start testing in Node 13, which will
> become the next LTS release from April 2020.
>
_Released on 2020-02-19._
## 4.0.1
- [`8dae99e`](https://github.com/sinonjs/formatio/commit/8dae99e19fb1f63707669aa18375aac377de92be)
Fix changes.md (Morgan Roderick)
- [`8dde8cb`](https://github.com/sinonjs/formatio/commit/8dde8cb370a2ea54f8d46ff43d1bf69a6ce661c5)
Use '--access public' for the publish command (Morgan Roderick)
_Released on 2019-12-19._
## 4.0.0
- [`8693846`](https://github.com/sinonjs/formatio/commit/869384686588e4c71612ce99e4b840842a0e5a46)
add support for formatting maps (#51) (Marc Redemske)
> * add support for formatting maps
> * Update @sinonjs/samsam to version that has isMap method
_Released on 2019-12-19._

View file

@ -1,27 +0,0 @@
(The BSD License)
Copyright (c) 2010-2012, Christian Johansen (christian@cjohansen.no) and
August Lilleaas (august.lilleaas@gmail.com). All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Christian Johansen nor the names of his contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View file

@ -1,102 +0,0 @@
# formatio
[![Build status](https://secure.travis-ci.org/sinonjs/formatio.svg?branch=master)](http://travis-ci.org/sinonjs/formatio)
[![codecov](https://codecov.io/gh/sinonjs/formatio/branch/master/graph/badge.svg)](https://codecov.io/gh/sinonjs/formatio)
<a href="CODE_OF_CONDUCT.md"><img src="https://img.shields.io/badge/Contributor%20Covenant-v2.0%20adopted-ff69b4.svg" alt="Contributor Covenant" /></a>
> The cheesy object formatter
Pretty formatting of arbitrary JavaScript values. Currently only supports ascii
formatting, suitable for command-line utilities. Like `JSON.stringify`, it
formats objects recursively, but unlike `JSON.stringify`, it can handle
regular expressions, functions, circular objects and more.
`formatio` is a general-purpose library. It works in browsers (including old
and rowdy ones, like IE6) and Node. It will define itself as an AMD module if
you want it to (i.e. if there's a `define` function available).
## Installation
```shell
npm install @sinonjs/formatio
```
## Documentation
https://sinonjs.github.io/formatio/
## Backers
Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/sinon#backer)]
<a href="https://opencollective.com/sinon/backer/0/website" target="_blank"><img src="https://opencollective.com/sinon/backer/0/avatar.svg"></a>
<a href="https://opencollective.com/sinon/backer/1/website" target="_blank"><img src="https://opencollective.com/sinon/backer/1/avatar.svg"></a>
<a href="https://opencollective.com/sinon/backer/2/website" target="_blank"><img src="https://opencollective.com/sinon/backer/2/avatar.svg"></a>
<a href="https://opencollective.com/sinon/backer/3/website" target="_blank"><img src="https://opencollective.com/sinon/backer/3/avatar.svg"></a>
<a href="https://opencollective.com/sinon/backer/4/website" target="_blank"><img src="https://opencollective.com/sinon/backer/4/avatar.svg"></a>
<a href="https://opencollective.com/sinon/backer/5/website" target="_blank"><img src="https://opencollective.com/sinon/backer/5/avatar.svg"></a>
<a href="https://opencollective.com/sinon/backer/6/website" target="_blank"><img src="https://opencollective.com/sinon/backer/6/avatar.svg"></a>
<a href="https://opencollective.com/sinon/backer/7/website" target="_blank"><img src="https://opencollective.com/sinon/backer/7/avatar.svg"></a>
<a href="https://opencollective.com/sinon/backer/8/website" target="_blank"><img src="https://opencollective.com/sinon/backer/8/avatar.svg"></a>
<a href="https://opencollective.com/sinon/backer/9/website" target="_blank"><img src="https://opencollective.com/sinon/backer/9/avatar.svg"></a>
<a href="https://opencollective.com/sinon/backer/10/website" target="_blank"><img src="https://opencollective.com/sinon/backer/10/avatar.svg"></a>
<a href="https://opencollective.com/sinon/backer/11/website" target="_blank"><img src="https://opencollective.com/sinon/backer/11/avatar.svg"></a>
<a href="https://opencollective.com/sinon/backer/12/website" target="_blank"><img src="https://opencollective.com/sinon/backer/12/avatar.svg"></a>
<a href="https://opencollective.com/sinon/backer/13/website" target="_blank"><img src="https://opencollective.com/sinon/backer/13/avatar.svg"></a>
<a href="https://opencollective.com/sinon/backer/14/website" target="_blank"><img src="https://opencollective.com/sinon/backer/14/avatar.svg"></a>
<a href="https://opencollective.com/sinon/backer/15/website" target="_blank"><img src="https://opencollective.com/sinon/backer/15/avatar.svg"></a>
<a href="https://opencollective.com/sinon/backer/16/website" target="_blank"><img src="https://opencollective.com/sinon/backer/16/avatar.svg"></a>
<a href="https://opencollective.com/sinon/backer/17/website" target="_blank"><img src="https://opencollective.com/sinon/backer/17/avatar.svg"></a>
<a href="https://opencollective.com/sinon/backer/18/website" target="_blank"><img src="https://opencollective.com/sinon/backer/18/avatar.svg"></a>
<a href="https://opencollective.com/sinon/backer/19/website" target="_blank"><img src="https://opencollective.com/sinon/backer/19/avatar.svg"></a>
<a href="https://opencollective.com/sinon/backer/20/website" target="_blank"><img src="https://opencollective.com/sinon/backer/20/avatar.svg"></a>
<a href="https://opencollective.com/sinon/backer/21/website" target="_blank"><img src="https://opencollective.com/sinon/backer/21/avatar.svg"></a>
<a href="https://opencollective.com/sinon/backer/22/website" target="_blank"><img src="https://opencollective.com/sinon/backer/22/avatar.svg"></a>
<a href="https://opencollective.com/sinon/backer/23/website" target="_blank"><img src="https://opencollective.com/sinon/backer/23/avatar.svg"></a>
<a href="https://opencollective.com/sinon/backer/24/website" target="_blank"><img src="https://opencollective.com/sinon/backer/24/avatar.svg"></a>
<a href="https://opencollective.com/sinon/backer/25/website" target="_blank"><img src="https://opencollective.com/sinon/backer/25/avatar.svg"></a>
<a href="https://opencollective.com/sinon/backer/26/website" target="_blank"><img src="https://opencollective.com/sinon/backer/26/avatar.svg"></a>
<a href="https://opencollective.com/sinon/backer/27/website" target="_blank"><img src="https://opencollective.com/sinon/backer/27/avatar.svg"></a>
<a href="https://opencollective.com/sinon/backer/28/website" target="_blank"><img src="https://opencollective.com/sinon/backer/28/avatar.svg"></a>
<a href="https://opencollective.com/sinon/backer/29/website" target="_blank"><img src="https://opencollective.com/sinon/backer/29/avatar.svg"></a>
## Sponsors
Become a sponsor and get your logo on our README on GitHub with a link to your site. [[Become a sponsor](https://opencollective.com/sinon#sponsor)]
<a href="https://opencollective.com/sinon/sponsor/0/website" target="_blank"><img src="https://opencollective.com/sinon/sponsor/0/avatar.svg"></a>
<a href="https://opencollective.com/sinon/sponsor/1/website" target="_blank"><img src="https://opencollective.com/sinon/sponsor/1/avatar.svg"></a>
<a href="https://opencollective.com/sinon/sponsor/2/website" target="_blank"><img src="https://opencollective.com/sinon/sponsor/2/avatar.svg"></a>
<a href="https://opencollective.com/sinon/sponsor/3/website" target="_blank"><img src="https://opencollective.com/sinon/sponsor/3/avatar.svg"></a>
<a href="https://opencollective.com/sinon/sponsor/4/website" target="_blank"><img src="https://opencollective.com/sinon/sponsor/4/avatar.svg"></a>
<a href="https://opencollective.com/sinon/sponsor/5/website" target="_blank"><img src="https://opencollective.com/sinon/sponsor/5/avatar.svg"></a>
<a href="https://opencollective.com/sinon/sponsor/6/website" target="_blank"><img src="https://opencollective.com/sinon/sponsor/6/avatar.svg"></a>
<a href="https://opencollective.com/sinon/sponsor/7/website" target="_blank"><img src="https://opencollective.com/sinon/sponsor/7/avatar.svg"></a>
<a href="https://opencollective.com/sinon/sponsor/8/website" target="_blank"><img src="https://opencollective.com/sinon/sponsor/8/avatar.svg"></a>
<a href="https://opencollective.com/sinon/sponsor/9/website" target="_blank"><img src="https://opencollective.com/sinon/sponsor/9/avatar.svg"></a>
<a href="https://opencollective.com/sinon/sponsor/10/website" target="_blank"><img src="https://opencollective.com/sinon/sponsor/10/avatar.svg"></a>
<a href="https://opencollective.com/sinon/sponsor/11/website" target="_blank"><img src="https://opencollective.com/sinon/sponsor/11/avatar.svg"></a>
<a href="https://opencollective.com/sinon/sponsor/12/website" target="_blank"><img src="https://opencollective.com/sinon/sponsor/12/avatar.svg"></a>
<a href="https://opencollective.com/sinon/sponsor/13/website" target="_blank"><img src="https://opencollective.com/sinon/sponsor/13/avatar.svg"></a>
<a href="https://opencollective.com/sinon/sponsor/14/website" target="_blank"><img src="https://opencollective.com/sinon/sponsor/14/avatar.svg"></a>
<a href="https://opencollective.com/sinon/sponsor/15/website" target="_blank"><img src="https://opencollective.com/sinon/sponsor/15/avatar.svg"></a>
<a href="https://opencollective.com/sinon/sponsor/16/website" target="_blank"><img src="https://opencollective.com/sinon/sponsor/16/avatar.svg"></a>
<a href="https://opencollective.com/sinon/sponsor/17/website" target="_blank"><img src="https://opencollective.com/sinon/sponsor/17/avatar.svg"></a>
<a href="https://opencollective.com/sinon/sponsor/18/website" target="_blank"><img src="https://opencollective.com/sinon/sponsor/18/avatar.svg"></a>
<a href="https://opencollective.com/sinon/sponsor/19/website" target="_blank"><img src="https://opencollective.com/sinon/sponsor/19/avatar.svg"></a>
<a href="https://opencollective.com/sinon/sponsor/20/website" target="_blank"><img src="https://opencollective.com/sinon/sponsor/20/avatar.svg"></a>
<a href="https://opencollective.com/sinon/sponsor/21/website" target="_blank"><img src="https://opencollective.com/sinon/sponsor/21/avatar.svg"></a>
<a href="https://opencollective.com/sinon/sponsor/22/website" target="_blank"><img src="https://opencollective.com/sinon/sponsor/22/avatar.svg"></a>
<a href="https://opencollective.com/sinon/sponsor/23/website" target="_blank"><img src="https://opencollective.com/sinon/sponsor/23/avatar.svg"></a>
<a href="https://opencollective.com/sinon/sponsor/24/website" target="_blank"><img src="https://opencollective.com/sinon/sponsor/24/avatar.svg"></a>
<a href="https://opencollective.com/sinon/sponsor/25/website" target="_blank"><img src="https://opencollective.com/sinon/sponsor/25/avatar.svg"></a>
<a href="https://opencollective.com/sinon/sponsor/26/website" target="_blank"><img src="https://opencollective.com/sinon/sponsor/26/avatar.svg"></a>
<a href="https://opencollective.com/sinon/sponsor/27/website" target="_blank"><img src="https://opencollective.com/sinon/sponsor/27/avatar.svg"></a>
<a href="https://opencollective.com/sinon/sponsor/28/website" target="_blank"><img src="https://opencollective.com/sinon/sponsor/28/avatar.svg"></a>
<a href="https://opencollective.com/sinon/sponsor/29/website" target="_blank"><img src="https://opencollective.com/sinon/sponsor/29/avatar.svg"></a>
## Licence
formatio was released under [BSD-3](LICENSE)

View file

@ -1,289 +0,0 @@
"use strict";
var samsam = require("@sinonjs/samsam");
var functionName = require("@sinonjs/commons").functionName;
var typeOf = require("@sinonjs/commons").typeOf;
var formatio = {
excludeConstructors: ["Object", /^.$/],
quoteStrings: true,
limitChildrenCount: 0
};
var specialObjects = [];
/* istanbul ignore else */
if (typeof global !== "undefined") {
specialObjects.push({ object: global, value: "[object global]" });
}
if (typeof document !== "undefined") {
specialObjects.push({
object: document,
value: "[object HTMLDocument]"
});
}
if (typeof window !== "undefined") {
specialObjects.push({ object: window, value: "[object Window]" });
}
function constructorName(f, object) {
var name = functionName(object && object.constructor);
var excludes = f.excludeConstructors || formatio.excludeConstructors;
var i, l;
for (i = 0, l = excludes.length; i < l; ++i) {
if (typeof excludes[i] === "string" && excludes[i] === name) {
return "";
} else if (excludes[i].test && excludes[i].test(name)) {
return "";
}
}
return name;
}
function isCircular(object, objects) {
if (typeof object !== "object") {
return false;
}
var i, l;
for (i = 0, l = objects.length; i < l; ++i) {
if (objects[i] === object) {
return true;
}
}
return false;
}
// eslint-disable-next-line complexity
function ascii(f, object, processed, indent) {
if (typeof object === "string") {
if (object.length === 0) {
return "(empty string)";
}
var qs = f.quoteStrings;
var quote = typeof qs !== "boolean" || qs;
// eslint-disable-next-line quotes
return processed || quote ? '"' + object + '"' : object;
}
if (typeof object === "symbol") {
return object.toString();
}
if (typeof object === "function" && !(object instanceof RegExp)) {
return ascii.func(object);
}
// eslint supports bigint as of version 6.0.0
// https://github.com/eslint/eslint/commit/e4ab0531c4e44c23494c6a802aa2329d15ac90e5
// eslint-disable-next-line
if (typeOf(object) === "bigint") {
return object.toString();
}
var internalProcessed = processed || [];
if (isCircular(object, internalProcessed)) {
return "[Circular]";
}
if (typeOf(object) === "array") {
return ascii.array.call(f, object, internalProcessed);
}
if (!object) {
return String(1 / object === -Infinity ? "-0" : object);
}
if (samsam.isElement(object)) {
return ascii.element(object);
}
if (
typeof object.toString === "function" &&
object.toString !== Object.prototype.toString
) {
return object.toString();
}
var i, l;
for (i = 0, l = specialObjects.length; i < l; i++) {
if (object === specialObjects[i].object) {
return specialObjects[i].value;
}
}
if (samsam.isSet(object)) {
return ascii.set.call(f, object, internalProcessed);
}
if (object instanceof Map) {
return ascii.map.call(f, object, internalProcessed);
}
return ascii.object.call(f, object, internalProcessed, indent);
}
ascii.func = function(func) {
var funcName = functionName(func) || "";
return "function " + funcName + "() {}";
};
function delimit(str, delimiters) {
var delims = delimiters || ["[", "]"];
return delims[0] + str + delims[1];
}
ascii.array = function(array, processed, delimiters) {
processed.push(array);
var pieces = [];
var i, l;
l =
this.limitChildrenCount > 0
? Math.min(this.limitChildrenCount, array.length)
: array.length;
for (i = 0; i < l; ++i) {
pieces.push(ascii(this, array[i], processed));
}
if (l < array.length) {
pieces.push("[... " + (array.length - l) + " more elements]");
}
return delimit(pieces.join(", "), delimiters);
};
ascii.set = function(set, processed) {
return ascii.array.call(this, Array.from(set), processed, ["Set {", "}"]);
};
ascii.map = function(map, processed) {
return ascii.array.call(this, Array.from(map), processed, ["Map [", "]"]);
};
function getSymbols(object) {
if (samsam.isArguments(object)) {
return [];
}
/* istanbul ignore else */
if (typeof Object.getOwnPropertySymbols === "function") {
return Object.getOwnPropertySymbols(object);
}
/* istanbul ignore next: This is only for IE, since getOwnPropertySymbols
* does not exist on Object there
*/
return [];
}
ascii.object = function(object, processed, indent) {
processed.push(object);
var internalIndent = indent || 0;
var pieces = [];
var properties = Object.keys(object)
.sort()
.concat(getSymbols(object));
var length = 3;
var prop, str, obj, i, k, l;
l =
this.limitChildrenCount > 0
? Math.min(this.limitChildrenCount, properties.length)
: properties.length;
for (i = 0; i < l; ++i) {
prop = properties[i];
obj = object[prop];
if (isCircular(obj, processed)) {
str = "[Circular]";
} else {
str = ascii(this, obj, processed, internalIndent + 2);
}
str =
(typeof prop === "string" && /\s/.test(prop)
? // eslint-disable-next-line quotes
'"' + prop + '"'
: prop.toString()) +
": " +
str;
length += str.length;
pieces.push(str);
}
var cons = constructorName(this, object);
var prefix = cons ? "[" + cons + "] " : "";
var is = "";
for (i = 0, k = internalIndent; i < k; ++i) {
is += " ";
}
if (l < properties.length) {
pieces.push("[... " + (properties.length - l) + " more elements]");
}
if (length + internalIndent > 80) {
return (
prefix + "{\n " + is + pieces.join(",\n " + is) + "\n" + is + "}"
);
}
return prefix + "{ " + pieces.join(", ") + " }";
};
ascii.element = function(element) {
var tagName = element.tagName.toLowerCase();
var attrs = element.attributes;
var pairs = [];
var attr, attrName, i, l, val;
for (i = 0, l = attrs.length; i < l; ++i) {
attr = attrs.item(i);
attrName = attr.nodeName.toLowerCase().replace("html:", "");
val = attr.nodeValue;
if (attrName !== "contenteditable" || val !== "inherit") {
if (val) {
// eslint-disable-next-line quotes
pairs.push(attrName + '="' + val + '"');
}
}
}
var formatted = "<" + tagName + (pairs.length > 0 ? " " : "");
// SVG elements have undefined innerHTML
var content = element.innerHTML || "";
if (content.length > 20) {
content = content.substr(0, 20) + "[...]";
}
var res =
formatted + pairs.join(" ") + ">" + content + "</" + tagName + ">";
return res.replace(/ contentEditable="inherit"/, "");
};
function Formatio(options) {
// eslint-disable-next-line guard-for-in
for (var opt in options) {
this[opt] = options[opt];
}
}
Formatio.prototype = {
functionName: functionName,
configure: function(options) {
return new Formatio(options);
},
constructorName: function(object) {
return constructorName(this, object);
},
ascii: function(object, processed, indent) {
return ascii(this, object, processed, indent);
}
};
module.exports = Formatio.prototype;

View file

@ -1,50 +0,0 @@
{
"name": "@sinonjs/formatio",
"version": "5.0.1",
"description": "Human-readable object formatting",
"homepage": "https://sinonjs.github.io/formatio/",
"author": "Christian Johansen",
"license": "BSD-3-Clause",
"main": "./lib/formatio",
"repository": {
"type": "git",
"url": "https://github.com/sinonjs/formatio.git"
},
"files": [
"lib/**/*[^test].js"
],
"scripts": {
"build": "npm run build:dist-folder && npm run build:bundle",
"build:bundle": "rollup -c > dist/formatio.js",
"build:dist-folder": "mkdirp dist",
"lint": "eslint .",
"prepublishOnly": "npm run build && mkdocs gh-deploy -r upstream || mkdocs gh-deploy -r origin",
"test": "mocha 'lib/**/*.test.js'",
"test-check-coverage": "npm run test-coverage && nyc check-coverage --branches 100 --functions 100 --lines 100",
"test-coverage": "nyc --reporter text --reporter html --reporter lcovonly npm run test",
"preversion": "npm run test-check-coverage",
"version": "changes --commits --footer",
"postversion": "git push --follow-tags && npm publish --access public"
},
"dependencies": {
"@sinonjs/commons": "^1",
"@sinonjs/samsam": "^5.0.2"
},
"devDependencies": {
"@sinonjs/referee": "^4.0.0",
"@studio/changes": "^2.0.0",
"eslint": "^6.5.1",
"eslint-config-prettier": "^6.4.0",
"eslint-config-sinon": "^3.0.1",
"eslint-plugin-ie11": "^1.0.0",
"eslint-plugin-mocha": "^6.1.1",
"eslint-plugin-prettier": "^3.1.1",
"jsdom": "^16.1.0",
"jsdom-global": "^3.0.2",
"mocha": "^7.0.1",
"nyc": "^15.0.0",
"prettier": "^1.18.2",
"rollup": "1.31.0",
"rollup-plugin-commonjs": "10.1.0"
}
}

View file

@ -1,5 +1,82 @@
# Changes
## 6.0.2
- [`144204d`](https://github.com/sinonjs/samsam/commit/144204d505526d5c382cb2f3dc2c2dd1378fe12d)
Fix deep equal comparison between promises (#217) (David G. Miguel)
_Released on 2021-05-24._
## 6.0.1
- [`decfafe`](https://github.com/sinonjs/samsam/commit/decfafe72d8b2d159cfc49440a8f4af6d3e9c574)
Bump y18n from 4.0.0 to 4.0.1 (dependabot[bot])
>
> Bumps [y18n](https://github.com/yargs/y18n) from 4.0.0 to 4.0.1.
> - [Release notes](https://github.com/yargs/y18n/releases)
> - [Changelog](https://github.com/yargs/y18n/blob/master/CHANGELOG.md)
> - [Commits](https://github.com/yargs/y18n/commits)
>
> Signed-off-by: dependabot[bot] <support@github.com>
_Released on 2021-04-08._
## 6.0.0
- [`95d1dce`](https://github.com/sinonjs/samsam/commit/95d1dce07f47b7bbb84111c42f44ecd9466dc2c8)
Use @sinonjs/eslint-config (Morgan Roderick)
>
> This drops support for legacy runtimes like IE11, legacy Edge, Safari 9 and the like
_Released on 2021-03-30._
## 5.3.1
- [`04e0faa`](https://github.com/sinonjs/samsam/commit/04e0faa88d8a08325c6d70febed9dad4e7eeabfe)
Distribute package as source (Morgan Roderick)
>
> This library is not meant for writing end user applications or even for
> being used directly when writing tests. It is not meant to be loaded
> directly by browsers.
>
> Consumers of this package are assumed to use their own bundlers, should
> they need to bundle code for use in browsers or workers.
>
> Therefore, it is safe to distribute the package as source files and not
> bundle them up.
>
> This allows us to remove the bundler and its transitive dependencies,
> which reduces the maintenance burden of managing the library.
>
_Released on 2021-01-13._
## 5.3.0
- [`fd8aabd`](https://github.com/sinonjs/samsam/commit/fd8aabd3768c199abc717dc6d793ef136419be72)
Generate .d.ts from JSDoc (Morgan Roderick)
>
> See https://humanwhocodes.com/snippets/2020/10/create-typescript-declarations-from-javascript-jsdoc/
>
_Released on 2020-11-16._
## 5.2.0
- [`f27b87c`](https://github.com/sinonjs/samsam/commit/f27b87cbd493a09e4a3181cf36f503facbbb23fb)
Add match.json (Maximilian Antoni)
_Released by [Maximilian Antoni](https://github.com/mantoni) on 2020-10-06._
## 5.1.0
- [`820c296`](https://github.com/sinonjs/samsam/commit/820c2961f70208367e1c072ae9a581eefd0d8d18)
Evaluate symbol keys for object matchers (#206) (Joel Bradshaw)
>
> * Make match() work for objects with symbol keys
_Released on 2020-08-11._
## 5.0.3
- [`9d2add0`](https://github.com/sinonjs/samsam/commit/9d2add01eba85eb17ddb91ac22404fb6c23e8d39)

View file

@ -43,7 +43,6 @@ Support us with a monthly donation and help us continue our activities. [[Become
<a href="https://opencollective.com/sinon/backer/28/website" target="_blank"><img src="https://opencollective.com/sinon/backer/28/avatar.svg"></a>
<a href="https://opencollective.com/sinon/backer/29/website" target="_blank"><img src="https://opencollective.com/sinon/backer/29/avatar.svg"></a>
## Sponsors
Become a sponsor and get your logo on our README on GitHub with a link to your site. [[Become a sponsor](https://opencollective.com/sinon#sponsor)]

File diff suppressed because it is too large Load diff

View file

@ -12,32 +12,27 @@ function available).
## Predicate functions
### `isArguments(value)`
Returns `true` if `value` is an `arguments` object, `false` otherwise.
### `isNegZero(value)`
Returns `true` if `value` is `-0`.
### `isElement(value)`
Returns `true` if `value` is a DOM element node. Unlike
Underscore.js/lodash, this function will return `false` if `value` is an
*element-like* object, i.e. a regular object with a `nodeType` property that
_element-like_ object, i.e. a regular object with a `nodeType` property that
holds the value `1`.
### `isSet(value)`
Returns `true` if `value` is a [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set).
## Comparison functions
### `identical(x, y)`
Strict equality check according to EcmaScript Harmony's `egal`.
@ -45,26 +40,24 @@ Strict equality check according to EcmaScript Harmony's `egal`.
**From the Harmony wiki:**
> An egal function simply makes available the internal `SameValue` function
from section 9.12 of the ES5 spec. If two values are egal, then they are not
observably distinguishable.
> from section 9.12 of the ES5 spec. If two values are egal, then they are not
> observably distinguishable.
`identical` returns `true` when `===` is `true`, except for `-0` and
`+0`, where it returns `false`. Additionally, it returns `true` when
`NaN` is compared to itself.
### `deepEqual(actual, expectation)`
Deep equal comparison. Two values are "deep equal" if:
* They are identical
* They are both date objects representing the same time
* They are both arrays containing elements that are all deepEqual
* They are objects with the same set of properties, and each property
in `actual` is deepEqual to the corresponding property in `expectation`
* `actual` can have [symbolic properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) that are missing from `expectation`
- They are identical
- They are both date objects representing the same time
- They are both arrays containing elements that are all deepEqual
- They are objects with the same set of properties, and each property
in `actual` is deepEqual to the corresponding property in `expectation`
- `actual` can have [symbolic properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) that are missing from `expectation`
### Matcher
@ -75,77 +68,62 @@ with these built in matchers:
Matches anything.
#### `sinon.match.defined`
Requires the value to be defined.
#### `sinon.match.truthy`
Requires the value to be truthy.
#### `sinon.match.falsy`
Requires the value to be falsy.
#### `sinon.match.bool`
Requires the value to be a `Boolean`
#### `sinon.match.number`
Requires the value to be a `Number`.
#### `sinon.match.string`
Requires the value to be a `String`.
#### `sinon.match.object`
Requires the value to be an `Object`.
#### `sinon.match.func`
Requires the value to be a `Function`.
#### `sinon.match.array`
Requires the value to be an `Array`.
#### `sinon.match.array.deepEquals(arr)`
Requires an `Array` to be deep equal another one.
#### `sinon.match.array.startsWith(arr)`
Requires an `Array` to start with the same values as another one.
#### `sinon.match.array.endsWith(arr)`
Requires an `Array` to end with the same values as another one.
#### `sinon.match.array.contains(arr)`
Requires an `Array` to contain each one of the values the given array has.
#### `sinon.match.map`
Requires the value to be a `Map`.
#### `sinon.match.map.deepEquals(map)`
Requires a `Map` to be deep equal another one.
@ -154,32 +132,26 @@ Requires a `Map` to be deep equal another one.
Requires a `Map` to contain each one of the items the given map has.
#### `sinon.match.set`
Requires the value to be a `Set`.
#### `sinon.match.set.deepEquals(set)`
Requires a `Set` to be deep equal another one.
#### `sinon.match.set.contains(set)`
Requires a `Set` to contain each one of the items the given set has.
#### `sinon.match.regexp`
Requires the value to be a regular expression.
#### `sinon.match.date`
Requires the value to be a `Date` object.
#### `sinon.match.symbol`
Requires the value to be a `Symbol`.
@ -195,18 +167,17 @@ Requires the value to strictly equal `ref`.
#### `sinon.match.typeOf(type)`
Requires the value to be of the given type, where `type` can be one of
`"undefined"`,
`"null"`,
`"boolean"`,
`"number"`,
`"string"`,
`"object"`,
`"function"`,
`"array"`,
`"regexp"`,
`"date"` or
`"symbol"`.
`"undefined"`,
`"null"`,
`"boolean"`,
`"number"`,
`"string"`,
`"object"`,
`"function"`,
`"array"`,
`"regexp"`,
`"date"` or
`"symbol"`.
#### `sinon.match.instanceOf(type)`
@ -222,24 +193,22 @@ The property might be inherited via the prototype chain. If the optional expecta
Same as `sinon.match.has` but the property must be defined by the value itself. Inherited properties are ignored.
#### `sinon.match.hasNested(propertyPath[, expectation])`
Requires the value to define the given `propertyPath`. Dot (`prop.prop`) and bracket (`prop[0]`) notations are supported as in [Lodash.get](https://lodash.com/docs/4.4.2#get).
The propertyPath might be inherited via the prototype chain. If the optional expectation is given, the value at the propertyPath is deeply compared with the expectation. The expectation can be another matcher.
```javascript
sinon.match.hasNested("a[0].b.c");
// Where actual is something like
var actual = { "a": [{ "b": { "c": 3 } }] };
var actual = { a: [{ b: { c: 3 } }] };
sinon.match.hasNested("a.b.c");
// Where actual is something like
var actual = { "a": { "b": { "c": 3 } } };
var actual = { a: { b: { c: 3 } } };
```
#### `sinon.match.every(matcher)`
@ -274,7 +243,14 @@ function returns `true` if the matcher is a case-insensitive substring of
```javascript
samsam.match("Give me something", "Give"); //true
samsam.match("Give me something", "sumptn"); // false
samsam.match({ toString: function () { return "yeah"; } }, "Yeah!"); // true
samsam.match(
{
toString: function () {
return "yeah";
},
},
"Yeah!"
); // true
```
The last example is not symmetric. When the matcher is a string, the `object`
@ -282,13 +258,11 @@ is coerced to a string - in this case using `toString`. Changing the order of
the arguments would cause the matcher to be an object, in which case different
rules apply (see below).
#### Boolean matcher
Performs a strict (i.e. `===`) match with the object. So, only `true`
matches `true`, and only `false` matches `false`.
#### Regular expression matcher
When the matcher is a regular expression, the function will pass if
@ -298,11 +272,17 @@ any object with a `test` method will be used as a matcher this way.
```javascript
samsam.match("Give me something", /^[a-z\s]$/i); // true
samsam.match("Give me something", /[0-9]/); // false
samsam.match({ toString: function () { return "yeah!"; } }, /yeah/); // true
samsam.match(
{
toString: function () {
return "yeah!";
},
},
/yeah/
); // true
samsam.match(234, /[a-z]/); // false
```
#### Number matcher
When the matcher is a number, the assertion will pass if `object == matcher`.
@ -310,11 +290,17 @@ When the matcher is a number, the assertion will pass if `object == matcher`.
```javascript
samsam.match("123", 123); // true
samsam.match("Give me something", 425); // false
samsam.match({ toString: function () { return "42"; } }, 42); // true
samsam.match(
{
toString: function () {
return "42";
},
},
42
); // true
samsam.match(234, 1234); // false
```
#### Function matcher
When the matcher is a function, it is called with `object` as its only
@ -334,17 +320,21 @@ samsam.match("Give me something", function () {
});
// true
samsam.match({
toString: function () {
return "42";
samsam.match(
{
toString: function () {
return "42";
},
},
function () {
return true;
}
}, function () { return true; });
);
// false
samsam.match(234, function () {});
```
#### Object matcher
As mentioned above, if an object matcher defines a `test` method, `match`
@ -354,32 +344,36 @@ If the matcher does not have a test method, a recursive match is performed. If
all properties of `matcher` matches corresponding properties in `object`,
`match` returns `true`. Note that the object matcher does not care if the
number of properties in the two objects are the same - only if all properties in
the matcher recursively matches ones in `object`.
the matcher recursively matches ones in `object`. If supported, this object matchers
include [symbolic properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol)
in the comparison.
```javascript
// true
samsam.match("123", {
test: function (arg) {
return arg == 123;
}
},
});
// false
samsam.match({}, { prop: 42 });
// true
samsam.match({
name: "Chris",
profession: "Programmer"
}, {
name: "Chris"
});
samsam.match(
{
name: "Chris",
profession: "Programmer",
},
{
name: "Chris",
}
);
// false
samsam.match(234, { name: "Chris" });
```
#### DOM elements
`match` can be very helpful when comparing DOM elements, because it allows
@ -391,6 +385,6 @@ var el = document.getElementById("myEl");
samsam.match(el, {
tagName: "h2",
className: "item",
innerHTML: "Howdy"
innerHTML: "Howdy",
});
```

Binary file not shown.

View file

@ -10,7 +10,7 @@ var ARRAY_TYPES = [
Int32Array,
Uint32Array,
Float32Array,
Float64Array
Float64Array,
];
module.exports = ARRAY_TYPES;

View file

@ -44,20 +44,20 @@ function createMatcher(expectation, message) {
if (arguments.length > 2) {
throw new TypeError(
"Expected 1 or 2 arguments, received " + arguments.length
`Expected 1 or 2 arguments, received ${arguments.length}`
);
}
if (type in TYPE_MAP) {
TYPE_MAP[type](m, expectation, message);
} else {
m.test = function(actual) {
m.test = function (actual) {
return deepEqual(actual, expectation);
};
}
if (!m.message) {
m.message = "match(" + valueToString(expectation) + ")";
m.message = `match(${valueToString(expectation)})`;
}
return m;
@ -65,48 +65,48 @@ function createMatcher(expectation, message) {
createMatcher.isMatcher = isMatcher;
createMatcher.any = createMatcher(function() {
createMatcher.any = createMatcher(function () {
return true;
}, "any");
createMatcher.defined = createMatcher(function(actual) {
createMatcher.defined = createMatcher(function (actual) {
return actual !== null && actual !== undefined;
}, "defined");
createMatcher.truthy = createMatcher(function(actual) {
createMatcher.truthy = createMatcher(function (actual) {
return Boolean(actual);
}, "truthy");
createMatcher.falsy = createMatcher(function(actual) {
createMatcher.falsy = createMatcher(function (actual) {
return !actual;
}, "falsy");
createMatcher.same = function(expectation) {
return createMatcher(function(actual) {
createMatcher.same = function (expectation) {
return createMatcher(function (actual) {
return expectation === actual;
}, "same(" + valueToString(expectation) + ")");
}, `same(${valueToString(expectation)})`);
};
createMatcher.in = function(arrayOfExpectations) {
createMatcher.in = function (arrayOfExpectations) {
if (typeOf(arrayOfExpectations) !== "array") {
throw new TypeError("array expected");
}
return createMatcher(function(actual) {
return some(arrayOfExpectations, function(expectation) {
return createMatcher(function (actual) {
return some(arrayOfExpectations, function (expectation) {
return expectation === actual;
});
}, "in(" + valueToString(arrayOfExpectations) + ")");
}, `in(${valueToString(arrayOfExpectations)})`);
};
createMatcher.typeOf = function(type) {
createMatcher.typeOf = function (type) {
assertType(type, "string", "type");
return createMatcher(function(actual) {
return createMatcher(function (actual) {
return typeOf(actual) === type;
}, 'typeOf("' + type + '")');
}, `typeOf("${type}")`);
};
createMatcher.instanceOf = function(type) {
createMatcher.instanceOf = function (type) {
/* istanbul ignore if */
if (
typeof Symbol === "undefined" ||
@ -121,9 +121,9 @@ createMatcher.instanceOf = function(type) {
"[Symbol.hasInstance]"
);
}
return createMatcher(function(actual) {
return createMatcher(function (actual) {
return actual instanceof type;
}, "instanceOf(" + (functionName(type) || objectToString(type)) + ")");
}, `instanceOf(${functionName(type) || objectToString(type)})`);
};
/**
@ -135,15 +135,15 @@ createMatcher.instanceOf = function(type) {
* @returns {object} A matcher
*/
function createPropertyMatcher(propertyTest, messagePrefix) {
return function(property, value) {
return function (property, value) {
assertType(property, "string", "property");
var onlyProperty = arguments.length === 1;
var message = messagePrefix + '("' + property + '"';
var message = `${messagePrefix}("${property}"`;
if (!onlyProperty) {
message += ", " + valueToString(value);
message += `, ${valueToString(value)}`;
}
message += ")";
return createMatcher(function(actual) {
return createMatcher(function (actual) {
if (
actual === undefined ||
actual === null ||
@ -156,26 +156,26 @@ function createPropertyMatcher(propertyTest, messagePrefix) {
};
}
createMatcher.has = createPropertyMatcher(function(actual, property) {
createMatcher.has = createPropertyMatcher(function (actual, property) {
if (typeof actual === "object") {
return property in actual;
}
return actual[property] !== undefined;
}, "has");
createMatcher.hasOwn = createPropertyMatcher(function(actual, property) {
createMatcher.hasOwn = createPropertyMatcher(function (actual, property) {
return hasOwnProperty(actual, property);
}, "hasOwn");
createMatcher.hasNested = function(property, value) {
createMatcher.hasNested = function (property, value) {
assertType(property, "string", "property");
var onlyProperty = arguments.length === 1;
var message = 'hasNested("' + property + '"';
var message = `hasNested("${property}"`;
if (!onlyProperty) {
message += ", " + valueToString(value);
message += `, ${valueToString(value)}`;
}
message += ")";
return createMatcher(function(actual) {
return createMatcher(function (actual) {
if (
actual === undefined ||
actual === null ||
@ -187,54 +187,78 @@ createMatcher.hasNested = function(property, value) {
}, message);
};
createMatcher.every = function(predicate) {
var jsonParseResultTypes = {
null: true,
boolean: true,
number: true,
string: true,
object: true,
array: true,
};
createMatcher.json = function (value) {
if (!jsonParseResultTypes[typeOf(value)]) {
throw new TypeError("Value cannot be the result of JSON.parse");
}
var message = `json(${JSON.stringify(value, null, " ")})`;
return createMatcher(function (actual) {
var parsed;
try {
parsed = JSON.parse(actual);
} catch (e) {
return false;
}
return deepEqual(parsed, value);
}, message);
};
createMatcher.every = function (predicate) {
assertMatcher(predicate);
return createMatcher(function(actual) {
return createMatcher(function (actual) {
if (typeOf(actual) === "object") {
return every(Object.keys(actual), function(key) {
return every(Object.keys(actual), function (key) {
return predicate.test(actual[key]);
});
}
return (
isIterable(actual) &&
every(actual, function(element) {
every(actual, function (element) {
return predicate.test(element);
})
);
}, "every(" + predicate.message + ")");
}, `every(${predicate.message})`);
};
createMatcher.some = function(predicate) {
createMatcher.some = function (predicate) {
assertMatcher(predicate);
return createMatcher(function(actual) {
return createMatcher(function (actual) {
if (typeOf(actual) === "object") {
return !every(Object.keys(actual), function(key) {
return !every(Object.keys(actual), function (key) {
return !predicate.test(actual[key]);
});
}
return (
isIterable(actual) &&
!every(actual, function(element) {
!every(actual, function (element) {
return !predicate.test(element);
})
);
}, "some(" + predicate.message + ")");
}, `some(${predicate.message})`);
};
createMatcher.array = createMatcher.typeOf("array");
createMatcher.array.deepEquals = function(expectation) {
return createMatcher(function(actual) {
createMatcher.array.deepEquals = function (expectation) {
return createMatcher(function (actual) {
// Comparing lengths is the fastest way to spot a difference before iterating through every item
var sameLength = actual.length === expectation.length;
return (
typeOf(actual) === "array" &&
sameLength &&
every(actual, function(element, index) {
every(actual, function (element, index) {
var expected = expectation[index];
return typeOf(expected) === "array" &&
typeOf(element) === "array"
@ -242,97 +266,97 @@ createMatcher.array.deepEquals = function(expectation) {
: deepEqual(expected, element);
})
);
}, "deepEquals([" + iterableToString(expectation) + "])");
}, `deepEquals([${iterableToString(expectation)}])`);
};
createMatcher.array.startsWith = function(expectation) {
return createMatcher(function(actual) {
createMatcher.array.startsWith = function (expectation) {
return createMatcher(function (actual) {
return (
typeOf(actual) === "array" &&
every(expectation, function(expectedElement, index) {
every(expectation, function (expectedElement, index) {
return actual[index] === expectedElement;
})
);
}, "startsWith([" + iterableToString(expectation) + "])");
}, `startsWith([${iterableToString(expectation)}])`);
};
createMatcher.array.endsWith = function(expectation) {
return createMatcher(function(actual) {
createMatcher.array.endsWith = function (expectation) {
return createMatcher(function (actual) {
// This indicates the index in which we should start matching
var offset = actual.length - expectation.length;
return (
typeOf(actual) === "array" &&
every(expectation, function(expectedElement, index) {
every(expectation, function (expectedElement, index) {
return actual[offset + index] === expectedElement;
})
);
}, "endsWith([" + iterableToString(expectation) + "])");
}, `endsWith([${iterableToString(expectation)}])`);
};
createMatcher.array.contains = function(expectation) {
return createMatcher(function(actual) {
createMatcher.array.contains = function (expectation) {
return createMatcher(function (actual) {
return (
typeOf(actual) === "array" &&
every(expectation, function(expectedElement) {
every(expectation, function (expectedElement) {
return arrayIndexOf(actual, expectedElement) !== -1;
})
);
}, "contains([" + iterableToString(expectation) + "])");
}, `contains([${iterableToString(expectation)}])`);
};
createMatcher.map = createMatcher.typeOf("map");
createMatcher.map.deepEquals = function mapDeepEquals(expectation) {
return createMatcher(function(actual) {
return createMatcher(function (actual) {
// Comparing lengths is the fastest way to spot a difference before iterating through every item
var sameLength = actual.size === expectation.size;
return (
typeOf(actual) === "map" &&
sameLength &&
every(actual, function(element, key) {
every(actual, function (element, key) {
return expectation.has(key) && expectation.get(key) === element;
})
);
}, "deepEquals(Map[" + iterableToString(expectation) + "])");
}, `deepEquals(Map[${iterableToString(expectation)}])`);
};
createMatcher.map.contains = function mapContains(expectation) {
return createMatcher(function(actual) {
return createMatcher(function (actual) {
return (
typeOf(actual) === "map" &&
every(expectation, function(element, key) {
every(expectation, function (element, key) {
return actual.has(key) && actual.get(key) === element;
})
);
}, "contains(Map[" + iterableToString(expectation) + "])");
}, `contains(Map[${iterableToString(expectation)}])`);
};
createMatcher.set = createMatcher.typeOf("set");
createMatcher.set.deepEquals = function setDeepEquals(expectation) {
return createMatcher(function(actual) {
return createMatcher(function (actual) {
// Comparing lengths is the fastest way to spot a difference before iterating through every item
var sameLength = actual.size === expectation.size;
return (
typeOf(actual) === "set" &&
sameLength &&
every(actual, function(element) {
every(actual, function (element) {
return expectation.has(element);
})
);
}, "deepEquals(Set[" + iterableToString(expectation) + "])");
}, `deepEquals(Set[${iterableToString(expectation)}])`);
};
createMatcher.set.contains = function setContains(expectation) {
return createMatcher(function(actual) {
return createMatcher(function (actual) {
return (
typeOf(actual) === "set" &&
every(expectation, function(element) {
every(expectation, function (element) {
return actual.has(element);
})
);
}, "contains(Set[" + iterableToString(expectation) + "])");
}, `contains(Set[${iterableToString(expectation)}])`);
};
createMatcher.bool = createMatcher.typeOf("boolean");

View file

@ -12,9 +12,7 @@
*/
function assertMethodExists(value, method, name, methodPath) {
if (value[method] === null || value[method] === undefined) {
throw new TypeError(
"Expected " + name + " to have method " + methodPath
);
throw new TypeError(`Expected ${name} to have method ${methodPath}`);
}
}

View file

@ -16,12 +16,7 @@ function assertType(value, type, name) {
var actual = typeOf(value);
if (actual !== type) {
throw new TypeError(
"Expected type of " +
name +
" to be " +
type +
", but was " +
actual
`Expected type of ${name} to be ${type}, but was ${actual}`
);
}
}

View file

@ -1,11 +1,16 @@
"use strict";
var every = require("@sinonjs/commons").prototypes.array.every;
var concat = require("@sinonjs/commons").prototypes.array.concat;
var typeOf = require("@sinonjs/commons").typeOf;
var deepEqualFactory = require("../deep-equal").use;
var isMatcher = require("./is-matcher");
var keys = Object.keys;
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
/**
* Matches `actual` with `expectation`
*
@ -21,7 +26,13 @@ function matchObject(actual, expectation, matcher) {
return false;
}
return every(Object.keys(expectation), function(key) {
var expectedKeys = keys(expectation);
/* istanbul ignore else: cannot collect coverage for engine that doesn't support Symbol */
if (typeOf(getOwnPropertySymbols) === "function") {
expectedKeys = concat(expectedKeys, getOwnPropertySymbols(expectation));
}
return every(expectedKeys, function (key) {
var exp = expectation[key];
var act = actual[key];

View file

@ -1,12 +1,12 @@
"use strict";
var matcherPrototype = {
toString: function() {
toString: function () {
return this.message;
}
},
};
matcherPrototype.or = function(valueOrMatcher) {
matcherPrototype.or = function (valueOrMatcher) {
var createMatcher = require("../create-matcher");
var isMatcher = createMatcher.isMatcher;
@ -19,14 +19,14 @@ matcherPrototype.or = function(valueOrMatcher) {
: createMatcher(valueOrMatcher);
var m1 = this;
var or = Object.create(matcherPrototype);
or.test = function(actual) {
or.test = function (actual) {
return m1.test(actual) || m2.test(actual);
};
or.message = m1.message + ".or(" + m2.message + ")";
or.message = `${m1.message}.or(${m2.message})`;
return or;
};
matcherPrototype.and = function(valueOrMatcher) {
matcherPrototype.and = function (valueOrMatcher) {
var createMatcher = require("../create-matcher");
var isMatcher = createMatcher.isMatcher;
@ -39,10 +39,10 @@ matcherPrototype.and = function(valueOrMatcher) {
: createMatcher(valueOrMatcher);
var m1 = this;
var and = Object.create(matcherPrototype);
and.test = function(actual) {
and.test = function (actual) {
return m1.test(actual) && m2.test(actual);
};
and.message = m1.message + ".and(" + m2.message + ")";
and.message = `${m1.message}.and(${m2.message})`;
return and;
};

View file

@ -8,54 +8,54 @@ var valueToString = require("@sinonjs/commons").valueToString;
var matchObject = require("./match-object");
var createTypeMap = function(match) {
var createTypeMap = function (match) {
return {
function: function(m, expectation, message) {
function: function (m, expectation, message) {
m.test = expectation;
m.message = message || "match(" + functionName(expectation) + ")";
m.message = message || `match(${functionName(expectation)})`;
},
number: function(m, expectation) {
m.test = function(actual) {
number: function (m, expectation) {
m.test = function (actual) {
// we need type coercion here
return expectation == actual; // eslint-disable-line eqeqeq
};
},
object: function(m, expectation) {
object: function (m, expectation) {
var array = [];
if (typeof expectation.test === "function") {
m.test = function(actual) {
m.test = function (actual) {
return expectation.test(actual) === true;
};
m.message = "match(" + functionName(expectation.test) + ")";
m.message = `match(${functionName(expectation.test)})`;
return m;
}
array = map(Object.keys(expectation), function(key) {
return key + ": " + valueToString(expectation[key]);
array = map(Object.keys(expectation), function (key) {
return `${key}: ${valueToString(expectation[key])}`;
});
m.test = function(actual) {
m.test = function (actual) {
return matchObject(actual, expectation, match);
};
m.message = "match(" + join(array, ", ") + ")";
m.message = `match(${join(array, ", ")})`;
return m;
},
regexp: function(m, expectation) {
m.test = function(actual) {
regexp: function (m, expectation) {
m.test = function (actual) {
return typeof actual === "string" && expectation.test(actual);
};
},
string: function(m, expectation) {
m.test = function(actual) {
string: function (m, expectation) {
m.test = function (actual) {
return (
typeof actual === "string" &&
stringIndexOf(actual, expectation) !== -1
);
};
m.message = 'match("' + expectation + '")';
}
m.message = `match("${expectation}")`;
},
};
};

View file

@ -24,7 +24,7 @@ function createSet(array) {
var items = typeOf(array) === "array" ? array : [];
var set = new Set();
forEach(items, function(item) {
forEach(items, function (item) {
set.add(item);
});

View file

@ -39,19 +39,19 @@ var complex1 = {
// eslint-disable-next-line no-undef
new Map(),
new Set(),
// eslint-disable-next-line no-undef, ie11/no-weak-collections
// eslint-disable-next-line no-undef
new WeakMap(),
// eslint-disable-next-line no-undef, ie11/no-weak-collections
new WeakSet()
]
}
}
// eslint-disable-next-line no-undef
new WeakSet(),
],
},
},
};
var complex2 = Object.create(complex1);
var cyclic1 = {
"4a092cd1-225e-4739-8331-d6564aafb702":
"d0cebbe0-23fb-4cc4-8fa0-ef11ceedf12e"
"d0cebbe0-23fb-4cc4-8fa0-ef11ceedf12e",
};
cyclic1.cyclicRef = cyclic1;
@ -59,14 +59,14 @@ var cyclic2 = Object.create(cyclic1);
// add tests
suite
.add("complex objects", function() {
.add("complex objects", function () {
return deepEqual(complex1, complex2);
})
.add("cyclic references", function() {
.add("cyclic references", function () {
return deepEqual(cyclic1, cyclic2);
})
// add listeners
.on("cycle", function(event) {
.on("cycle", function (event) {
// eslint-disable-next-line no-console
console.log(String(event.target));
})

View file

@ -117,6 +117,10 @@ function deepEqualCyclic(actual, expectation, match) {
}
}
if (actualObj instanceof Promise && expectationObj instanceof Promise) {
return actualObj === expectationObj;
}
if (actualObj instanceof Error && expectationObj instanceof Error) {
return actualObj === expectationObj;
}
@ -176,7 +180,7 @@ function deepEqualCyclic(actual, expectation, match) {
}
var mapsDeeplyEqual = true;
mapForEach(actualObj, function(value, key) {
mapForEach(actualObj, function (value, key) {
mapsDeeplyEqual =
mapsDeeplyEqual &&
deepEqualCyclic(value, expectationObj.get(key));
@ -185,7 +189,7 @@ function deepEqualCyclic(actual, expectation, match) {
return mapsDeeplyEqual;
}
return every(expectationKeysAndSymbols, function(key) {
return every(expectationKeysAndSymbols, function (key) {
if (!hasOwnProperty(actualObj, key)) {
return false;
}
@ -210,11 +214,11 @@ function deepEqualCyclic(actual, expectation, match) {
var newActualPath =
actualIndex !== -1
? actualPaths[actualIndex]
: actualPath + "[" + JSON.stringify(key) + "]";
: `${actualPath}[${JSON.stringify(key)}]`;
var newExpectationPath =
expectationIndex !== -1
? expectationPaths[expectationIndex]
: expectationPath + "[" + JSON.stringify(key) + "]";
: `${expectationPath}[${JSON.stringify(key)}]`;
var combinedPath = newActualPath + newExpectationPath;
// stop recursion if current objects are already compared
@ -251,7 +255,7 @@ function deepEqualCyclic(actual, expectation, match) {
})(actual, expectation, "$1", "$2");
}
deepEqualCyclic.use = function(match) {
deepEqualCyclic.use = function (match) {
return function deepEqual(a, b) {
return deepEqualCyclic(a, b, match);
};

View file

@ -14,9 +14,9 @@ var forEach = require("@sinonjs/commons").prototypes.set.forEach;
*/
function isSubset(s1, s2, compare) {
var allContained = true;
forEach(s1, function(v1) {
forEach(s1, function (v1) {
var includes = false;
forEach(s2, function(v2) {
forEach(s2, function (v2) {
if (compare(v2, v1)) {
includes = true;
}

View file

@ -29,9 +29,9 @@ function iterableToString(obj) {
function mapToString(map) {
var representation = "";
/* eslint-disable-next-line local-rules/no-prototype-methods */
map.forEach(function(value, key) {
representation += "[" + stringify(key) + "," + stringify(value) + "],";
// eslint-disable-next-line @sinonjs/no-prototype-methods/no-prototype-methods
map.forEach(function (value, key) {
representation += `[${stringify(key)},${stringify(value)}],`;
});
representation = slice(representation, 0, -1);
@ -48,9 +48,9 @@ function mapToString(map) {
function genericIterableToString(iterable) {
var representation = "";
/* eslint-disable-next-line local-rules/no-prototype-methods */
iterable.forEach(function(value) {
representation += stringify(value) + ",";
// eslint-disable-next-line @sinonjs/no-prototype-methods/no-prototype-methods
iterable.forEach(function (value) {
representation += `${stringify(value)},`;
});
representation = slice(representation, 0, -1);
@ -65,7 +65,7 @@ function genericIterableToString(iterable) {
* @returns {string} A string representation of `item`
*/
function stringify(item) {
return typeof item === "string" ? "'" + item + "'" : valueToString(item);
return typeof item === "string" ? `'${item}'` : valueToString(item);
}
module.exports = iterableToString;

View file

@ -167,7 +167,7 @@ function match(object, matcherOrValue) {
}
/* eslint-enable complexity */
forEach(Object.keys(createMatcher), function(key) {
forEach(Object.keys(createMatcher), function (key) {
match[key] = createMatcher[key];
});

View file

@ -22,5 +22,5 @@ module.exports = {
isMap: isMap,
isNegZero: isNegZero,
isSet: isSet,
match: match
match: match,
};

View file

@ -1,23 +1,23 @@
{
"name": "@sinonjs/samsam",
"version": "5.0.3",
"version": "6.0.2",
"description": "Value identification and comparison functions",
"homepage": "http://sinonjs.github.io/samsam/",
"author": "Christian Johansen",
"license": "BSD-3-Clause",
"main": "./lib/samsam",
"types": "./types/samsam.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/sinonjs/samsam.git"
},
"lint-staged": {
"*.{js,css,md}": "prettier --check",
"*.js": "eslint"
},
"scripts": {
"benchmark": "node lib/deep-equal-benchmark.js",
"build": "run-s build:dist-folder build:bundle",
"build:bundle": "rollup -c",
"build:dist-folder": "mkdirp dist",
"build": "rm -rf types && tsc",
"jsdoc": "jsdoc -c jsdoc.conf.json",
"lint": "eslint .",
"prepublishOnly": "npm run build && mkdocs gh-deploy -r upstream || mkdocs gh-deploy -r origin",
@ -26,6 +26,8 @@
"test-check-coverage": "npm run test-coverage && nyc check-coverage --branches 100 --functions 100 --lines 100",
"test-coverage": "nyc --all --reporter text --reporter html --reporter lcovonly npm run test",
"test-headless": "mochify --no-detect-globals --recursive -R dot --plugin [ proxyquire-universal ] \"./lib/*.test.js\"",
"prettier:check": "prettier --check '**/*.{js,css,md}'",
"prettier:write": "prettier --write '**/*.{js,css,md}'",
"preversion": "npm run test-check-coverage",
"version": "changes --commits --footer",
"postversion": "git push --follow-tags && npm publish --access public"
@ -35,10 +37,10 @@
"jsdom-global": false
},
"files": [
"dist/",
"docs/",
"lib/",
"!lib/**/*.test.js"
"!lib/**/*.test.js",
"types/"
],
"dependencies": {
"@sinonjs/commons": "^1.6.0",
@ -46,17 +48,11 @@
"type-detect": "^4.0.8"
},
"devDependencies": {
"@sinonjs/referee": "^4.0.0",
"@sinonjs/eslint-config": "^4.0.0",
"@sinonjs/eslint-plugin-no-prototype-methods": "^0.1.0",
"@sinonjs/referee": "^5.0.0",
"@studio/changes": "^2.0.0",
"benchmark": "2.1.4",
"eslint": "^6.2.0",
"eslint-config-prettier": "^6.1.0",
"eslint-config-sinon": "^3.0.1",
"eslint-plugin-ie11": "^1.0.0",
"eslint-plugin-jsdoc": "^21.0.0",
"eslint-plugin-local-rules": "^0.1.1",
"eslint-plugin-mocha": "^6.0.0",
"eslint-plugin-prettier": "^3.1.0",
"husky": "^4.2.1",
"jquery": "^3.4.1",
"jsdoc": "^3.6.3",
@ -67,14 +63,12 @@
"mkdirp": "^1.0.3",
"mocha": "^7.0.1",
"mochify": "^6.6.0",
"npm-run-all": "^4.1.2",
"nyc": "^15.0.0",
"prettier": "^1.18.2",
"prettier": "^2.2.1",
"proxyquire": "^2.1.3",
"proxyquire-universal": "^2.1.0",
"proxyquireify": "^3.2.1",
"rollup": "^1.23.0",
"rollup-plugin-commonjs": "^10.1.0"
"typescript": "^4.0.5"
},
"nyc": {
"exclude": [
@ -87,5 +81,10 @@
"rollup.config.js",
"lib/deep-equal-benchmark.js"
]
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
}
}

2
node_modules/@sinonjs/samsam/types/array-types.d.ts generated vendored Normal file
View file

@ -0,0 +1,2 @@
export = ARRAY_TYPES;
declare var ARRAY_TYPES: (ArrayConstructor | Int8ArrayConstructor)[];

40
node_modules/@sinonjs/samsam/types/create-matcher.d.ts generated vendored Normal file
View file

@ -0,0 +1,40 @@
export = createMatcher;
/**
* Creates a matcher object for the passed expectation
*
* @alias module:samsam.createMatcher
* @param {*} expectation An expecttation
* @param {string} message A message for the expectation
* @returns {object} A matcher object
*/
declare function createMatcher(expectation: any, message: string, ...args: any[]): object;
declare namespace createMatcher {
export { isMatcher };
export const any: any;
export const defined: any;
export const truthy: any;
export const falsy: any;
export function same(expectation: any): any;
function _in(arrayOfExpectations: any): any;
export { _in as in };
export function typeOf(type: any): any;
export function instanceOf(type: any): any;
export const has: any;
export const hasOwn: any;
export function hasNested(property: any, value: any, ...args: any[]): any;
export function json(value: any): any;
export function every(predicate: any): any;
export function some(predicate: any): any;
export const array: any;
export const map: any;
export const set: any;
export const bool: any;
export const number: any;
export const string: any;
export const object: any;
export const func: any;
export const regexp: any;
export const date: any;
export const symbol: any;
}
declare var isMatcher: typeof import("./create-matcher/is-matcher");

View file

@ -0,0 +1,8 @@
export = assertMatcher;
/**
* Throws a TypeError when `value` is not a matcher
*
* @private
* @param {*} value The value to examine
*/
declare function assertMatcher(value: any): void;

View file

@ -0,0 +1,12 @@
export = assertMethodExists;
/**
* Throws a TypeError when expected method doesn't exist
*
* @private
* @param {*} value A value to examine
* @param {string} method The name of the method to look for
* @param {name} name A name to use for the error message
* @param {string} methodPath The name of the method to use for error messages
* @throws {TypeError} When the method doesn't exist
*/
declare function assertMethodExists(value: any, method: string, name: never, methodPath: string): void;

View file

@ -0,0 +1,12 @@
export = assertType;
/**
* Ensures that value is of type
*
* @private
* @param {*} value A value to examine
* @param {string} type A basic JavaScript type to compare to, e.g. "object", "string"
* @param {string} name A string to use for the error message
* @throws {TypeError} If value is not of the expected type
* @returns {undefined}
*/
declare function assertType(value: any, type: string, name: string): undefined;

View file

@ -0,0 +1,9 @@
export = isIterable;
/**
* Returns `true` for iterables
*
* @private
* @param {*} value A value to examine
* @returns {boolean} Returns `true` when `value` looks like an iterable
*/
declare function isIterable(value: any): boolean;

View file

@ -0,0 +1,9 @@
export = isMatcher;
/**
* Returns `true` when `object` is a matcher
*
* @private
* @param {*} object A value to examine
* @returns {boolean} Returns `true` when `object` is a matcher
*/
declare function isMatcher(object: any): boolean;

View file

@ -0,0 +1,11 @@
export = matchObject;
/**
* Matches `actual` with `expectation`
*
* @private
* @param {*} actual A value to examine
* @param {object} expectation An object with properties to match on
* @param {object} matcher A matcher to use for comparison
* @returns {boolean} Returns true when `actual` matches all properties in `expectation`
*/
declare function matchObject(actual: any, expectation: object, matcher: object): boolean;

View file

@ -0,0 +1,2 @@
export function or(valueOrMatcher: any, ...args: any[]): any;
export function and(valueOrMatcher: any, ...args: any[]): any;

View file

@ -0,0 +1,8 @@
export = createTypeMap;
declare function createTypeMap(match: any): {
function: (m: any, expectation: any, message: any) => void;
number: (m: any, expectation: any) => void;
object: (m: any, expectation: any) => any;
regexp: (m: any, expectation: any) => void;
string: (m: any, expectation: any) => void;
};

13
node_modules/@sinonjs/samsam/types/create-set.d.ts generated vendored Normal file
View file

@ -0,0 +1,13 @@
export = createSet;
/**
* This helper makes it convenient to create Set instances from a
* collection, an overcomes the shortcoming that IE11 doesn't support
* collection arguments
*
* @private
* @param {Array} array An array to create a set from
* @returns {Set} A set (unique) containing the members from array
*
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
*/
declare function createSet(array: any[], ...args: any[]): any;

View file

@ -0,0 +1 @@
export {};

22
node_modules/@sinonjs/samsam/types/deep-equal.d.ts generated vendored Normal file
View file

@ -0,0 +1,22 @@
export = deepEqualCyclic;
/**
* Deep equal comparison. Two values are "deep equal" when:
*
* - They are equal, according to samsam.identical
* - They are both date objects representing the same time
* - They are both arrays containing elements that are all deepEqual
* - They are objects with the same set of properties, and each property
* in ``actual`` is deepEqual to the corresponding property in ``expectation``
*
* Supports cyclic objects.
*
* @alias module:samsam.deepEqual
* @param {*} actual The object to examine
* @param {*} expectation The object actual is expected to be equal to
* @param {object} match A value to match on
* @returns {boolean} Returns true when actual and expectation are considered equal
*/
declare function deepEqualCyclic(actual: any, expectation: any, match: object): boolean;
declare namespace deepEqualCyclic {
function use(match: any): (a: any, b: any) => boolean;
}

11
node_modules/@sinonjs/samsam/types/get-class.d.ts generated vendored Normal file
View file

@ -0,0 +1,11 @@
export = getClass;
/**
* Returns the internal `Class` by calling `Object.prototype.toString`
* with the provided value as `this`. Return value is a `String`, naming the
* internal class, e.g. "Array"
*
* @private
* @param {*} value - Any value
* @returns {string} - A string representation of the `Class` of `value`
*/
declare function getClass(value: any): string;

19
node_modules/@sinonjs/samsam/types/identical.d.ts generated vendored Normal file
View file

@ -0,0 +1,19 @@
export = identical;
/**
* Strict equality check according to EcmaScript Harmony's `egal`.
*
* **From the Harmony wiki:**
* > An `egal` function simply makes available the internal `SameValue` function
* > from section 9.12 of the ES5 spec. If two values are egal, then they are not
* > observably distinguishable.
*
* `identical` returns `true` when `===` is `true`, except for `-0` and
* `+0`, where it returns `false`. Additionally, it returns `true` when
* `NaN` is compared to itself.
*
* @alias module:samsam.identical
* @param {*} obj1 The first value to compare
* @param {*} obj2 The second value to compare
* @returns {boolean} Returns `true` when the objects are *egal*, `false` otherwise
*/
declare function identical(obj1: any, obj2: any): boolean;

9
node_modules/@sinonjs/samsam/types/is-arguments.d.ts generated vendored Normal file
View file

@ -0,0 +1,9 @@
export = isArguments;
/**
* Returns `true` when `object` is an `arguments` object, `false` otherwise
*
* @alias module:samsam.isArguments
* @param {*} object - The object to examine
* @returns {boolean} `true` when `object` is an `arguments` object
*/
declare function isArguments(object: any): boolean;

View file

@ -0,0 +1,9 @@
export = isArrayType;
/**
* Returns `true` when `object` is an array type, `false` otherwise
*
* @param {*} object - The object to examine
* @returns {boolean} `true` when `object` is an array type
* @private
*/
declare function isArrayType(object: any): boolean;

9
node_modules/@sinonjs/samsam/types/is-date.d.ts generated vendored Normal file
View file

@ -0,0 +1,9 @@
export = isDate;
/**
* Returns `true` when `value` is an instance of Date
*
* @private
* @param {Date} value The value to examine
* @returns {boolean} `true` when `value` is an instance of Date
*/
declare function isDate(value: Date): boolean;

13
node_modules/@sinonjs/samsam/types/is-element.d.ts generated vendored Normal file
View file

@ -0,0 +1,13 @@
export = isElement;
/**
* Returns `true` when `object` is a DOM element node.
*
* Unlike Underscore.js/lodash, this function will return `false` if `object`
* is an *element-like* object, i.e. a regular object with a `nodeType`
* property that holds the value `1`.
*
* @alias module:samsam.isElement
* @param {object} object The object to examine
* @returns {boolean} Returns `true` for DOM element nodes
*/
declare function isElement(object: object): boolean;

9
node_modules/@sinonjs/samsam/types/is-map.d.ts generated vendored Normal file
View file

@ -0,0 +1,9 @@
export = isMap;
/**
* Returns `true` when `value` is a Map
*
* @param {*} value A value to examine
* @returns {boolean} `true` when `value` is an instance of `Map`, `false` otherwise
* @private
*/
declare function isMap(value: any): boolean;

9
node_modules/@sinonjs/samsam/types/is-nan.d.ts generated vendored Normal file
View file

@ -0,0 +1,9 @@
export = isNaN;
/**
* Compares a `value` to `NaN`
*
* @private
* @param {*} value A value to examine
* @returns {boolean} Returns `true` when `value` is `NaN`
*/
declare function isNaN(value: any): boolean;

9
node_modules/@sinonjs/samsam/types/is-neg-zero.d.ts generated vendored Normal file
View file

@ -0,0 +1,9 @@
export = isNegZero;
/**
* Returns `true` when `value` is `-0`
*
* @alias module:samsam.isNegZero
* @param {*} value A value to examine
* @returns {boolean} Returns `true` when `value` is `-0`
*/
declare function isNegZero(value: any): boolean;

16
node_modules/@sinonjs/samsam/types/is-object.d.ts generated vendored Normal file
View file

@ -0,0 +1,16 @@
export = isObject;
/**
* Returns `true` when the value is a regular Object and not a specialized Object
*
* This helps speed up deepEqual cyclic checks
*
* The premise is that only Objects are stored in the visited array.
* So if this function returns false, we don't have to do the
* expensive operation of searching for the value in the the array of already
* visited objects
*
* @private
* @param {object} value The object to examine
* @returns {boolean} `true` when the object is a non-specialised object
*/
declare function isObject(value: object): boolean;

9
node_modules/@sinonjs/samsam/types/is-set.d.ts generated vendored Normal file
View file

@ -0,0 +1,9 @@
export = isSet;
/**
* Returns `true` when the argument is an instance of Set, `false` otherwise
*
* @alias module:samsam.isSet
* @param {*} val - A value to examine
* @returns {boolean} Returns `true` when the argument is an instance of Set, `false` otherwise
*/
declare function isSet(val: any): boolean;

12
node_modules/@sinonjs/samsam/types/is-subset.d.ts generated vendored Normal file
View file

@ -0,0 +1,12 @@
export = isSubset;
/**
* Returns `true` when `s1` is a subset of `s2`, `false` otherwise
*
* @private
* @param {Array|Set} s1 The target value
* @param {Array|Set} s2 The containing value
* @param {Function} compare A comparison function, should return `true` when
* values are considered equal
* @returns {boolean} Returns `true` when `s1` is a subset of `s2`, `false`` otherwise
*/
declare function isSubset(s1: any[] | any, s2: any[] | any, compare: Function): boolean;

View file

@ -0,0 +1,9 @@
export = iterableToString;
/**
* Creates a string represenation of an iterable object
*
* @private
* @param {object} obj The iterable object to stringify
* @returns {string} A string representation
*/
declare function iterableToString(obj: object): string;

10
node_modules/@sinonjs/samsam/types/match.d.ts generated vendored Normal file
View file

@ -0,0 +1,10 @@
export = match;
/**
* Matches an object with a matcher (or value)
*
* @alias module:samsam.match
* @param {object} object The object candidate to match
* @param {object} matcherOrValue A matcher or value to match against
* @returns {boolean} true when `object` matches `matcherOrValue`
*/
declare function match(object: object, matcherOrValue: object): boolean;

13
node_modules/@sinonjs/samsam/types/samsam.d.ts generated vendored Normal file
View file

@ -0,0 +1,13 @@
export var createMatcher: typeof import("./create-matcher");
declare var deepEqualCyclic: (a: any, b: any) => boolean;
/**
* @module samsam
*/
export var identical: typeof import("./identical");
export var isArguments: typeof import("./is-arguments");
export var isElement: typeof import("./is-element");
export var isMap: typeof import("./is-map");
export var isNegZero: typeof import("./is-neg-zero");
export var isSet: typeof import("./is-set");
export var match: typeof import("./match");
export { deepEqualCyclic as deepEqual };