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

jest-matchers

Package Overview
Dependencies
Maintainers
4
Versions
50
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

jest-matchers - npm Package Compare versions

Comparing version 15.1.1 to 15.2.0-alpha.c681f819

55

build/index.js

@@ -22,2 +22,4 @@ /**

const matchers = require('./matchers');

@@ -29,11 +31,11 @@ const spyMatchers = require('./spyMatchers');

const GLOBAL_MATCHERS_OBJECT_SYMBOL = Symbol.for('$$jest-matchers-object');
const GLOBAL_STATE = Symbol.for('$$jest-matchers-object');
class JestAssertionError extends Error {}
if (!global[GLOBAL_MATCHERS_OBJECT_SYMBOL]) {
if (!global[GLOBAL_STATE]) {
Object.defineProperty(
global,
GLOBAL_MATCHERS_OBJECT_SYMBOL,
{ value: Object.create(null) });
GLOBAL_STATE,
{ value: { matchers: Object.create(null), state: { suppressedErrors: [] } } });

@@ -43,3 +45,3 @@ }

const expect = actual => {
const allMatchers = global[GLOBAL_MATCHERS_OBJECT_SYMBOL];
const allMatchers = global[GLOBAL_STATE].matchers;
const expectation = { not: {} };

@@ -61,11 +63,21 @@ Object.keys(allMatchers).forEach(name => {

{
return function throwingMatcher(expected, options) {
return function throwingMatcher(expected) {
let throws = true;
const matcherContext = Object.assign(
// When throws is disabled, the matcher will not throw errors during test
// execution but instead add them to the global matcher state. If a
// matcher throws, test execution is normally stopped immediately. The
// snapshot matcher uses it because we want to log all snapshot
// failures in a test.
{ dontThrow: () => throws = false },
global[GLOBAL_STATE].state,
{ isNot });
let result;
try {
result = matcher(
actual,
expected,
options,
{ args: arguments });
try {for (var _len = arguments.length, rest = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {rest[_key - 1] = arguments[_key];}
result = matcher.apply(
matcherContext,
[actual, expected].concat(rest));
} catch (error) {

@@ -91,3 +103,8 @@ // Remove this and deeper functions from the stack trace frame.

Error.captureStackTrace(error, throwingMatcher);
throw error;
if (throws) {
throw error;
} else {
global[GLOBAL_STATE].state.suppressedErrors.push(error);
}
}

@@ -98,3 +115,3 @@ };

const addMatchers = matchersObj => {
Object.assign(global[GLOBAL_MATCHERS_OBJECT_SYMBOL], matchersObj);
Object.assign(global[GLOBAL_STATE].matchers, matchersObj);
};

@@ -121,2 +138,8 @@

const setState = state => {
Object.assign(global[GLOBAL_STATE].state, state);
};
const getState = () => global[GLOBAL_STATE].state;
// add default jest matchers

@@ -129,2 +152,4 @@ addMatchers(matchers);

addMatchers,
expect };
expect,
getState,
setState };

@@ -16,2 +16,4 @@ /**

const diff = require('jest-diff');var _require =

@@ -115,4 +117,33 @@ require('jest-util');const escapeStrForRegex = _require.escapeStrForRegex;var _require2 =

toBeInstanceOf(received, constructor) {
const constType = getType(constructor);
if (constType !== 'function') {
throw new Error(
matcherHint('[.not].toBeInstanceOf', 'value', 'constructor') + `\n\n` +
`Expected constructor to be a function. Instead got:\n` +
` ${ printExpected(constType) }`);
}
const pass = received instanceof constructor;
const message = pass ?
() => matcherHint('.not.toBeInstanceOf', 'value', 'constructor') + '\n\n' +
`Expected value not to be an instance of:\n` +
` ${ printExpected(constructor.name || constructor) }\n` +
`Received:\n` +
` ${ printReceived(received) }\n` :
() => matcherHint('.toBeInstanceOf', 'value', 'constructor') + '\n\n' +
`Expected value to be an instance of:\n` +
` ${ printExpected(constructor.name || constructor) }\n` +
`Received:\n` +
` ${ printReceived(received) }\n` +
`Constructor:\n` +
` ${ printReceived(received.constructor && received.constructor.name) }`;
return { message, pass };
},
toBeTruthy(actual, expected) {
ensureNoExpected(expected, 'toBeTruthy');
ensureNoExpected(expected, '.toBeTruthy');
const pass = !!actual;

@@ -130,3 +161,3 @@ const message = pass ?

toBeFalsy(actual, expected) {
ensureNoExpected(expected, 'toBeFalsy');
ensureNoExpected(expected, '.toBeFalsy');
const pass = !actual;

@@ -144,3 +175,3 @@ const message = pass ?

toBeNaN(actual, expected) {
ensureNoExpected(expected, 'toBeNaN');
ensureNoExpected(expected, '.toBeNaN');
const pass = Number.isNaN(actual);

@@ -158,3 +189,3 @@ const message = pass ?

toBeNull(actual, expected) {
ensureNoExpected(expected, 'toBeNull');
ensureNoExpected(expected, '.toBeNull');
const pass = actual === null;

@@ -172,3 +203,3 @@ const message = pass ?

toBeDefined(actual, expected) {
ensureNoExpected(expected, 'toBeDefined');
ensureNoExpected(expected, '.toBeDefined');
const pass = actual !== void 0;

@@ -186,3 +217,3 @@ const message = pass ?

toBeUndefined(actual, expected) {
ensureNoExpected(expected, 'toBeUndefined');
ensureNoExpected(expected, '.toBeUndefined');
const pass = actual === void 0;

@@ -293,3 +324,33 @@ const message = pass ?

toBeCloseTo(actual, expected) {let precision = arguments.length <= 2 || arguments[2] === undefined ? 2 : arguments[2];
toContainEqual(collection, value) {
const collectionType = getType(collection);
if (!Array.isArray(collection)) {
throw new Error(
`.toContainEqual() only works with arrays.\n` +
printWithType('Received', collection, printReceived));
}
const pass =
collection.findIndex(item => equals(item, value, [iterableEquality])) !== -1;
const message = pass ?
() => matcherHint('.not.toContainEqual', collectionType, 'value') + '\n\n' +
`Expected ${ collectionType }:\n` +
` ${ printReceived(collection) }\n` +
`Not to contain a value equal to:\n` +
` ${ printExpected(value) }\n` :
() => matcherHint('.toContainEqual', collectionType, 'value') + '\n\n' +
`Expected ${ collectionType }:\n` +
` ${ printReceived(collection) }\n` +
`To contain a value equal to:\n` +
` ${ printExpected(value) }`;
return { message, pass };
},
toBeCloseTo(
actual,
expected)
{let precision = arguments.length <= 2 || arguments[2] === undefined ? 2 : arguments[2];
ensureNumbers(actual, expected, '.toBeCloseTo');

@@ -316,3 +377,3 @@ const pass = Math.abs(expected - actual) < Math.pow(10, -precision) / 2;

matcherHint('[.not].toMatch', 'string', 'expected') + '\n\n' +
`${ RECEIVED_COLOR('string') } value should be a string.\n` +
`${ RECEIVED_COLOR('string') } value must be a string.\n` +
printWithType('Received', received, printReceived));

@@ -322,7 +383,6 @@

const isString = typeof expected == 'string';
if (!(expected instanceof RegExp) && !isString) {
if (!(expected instanceof RegExp) && !(typeof expected === 'string')) {
throw new Error(
matcherHint('[.not].toMatch', 'string', 'expected') + '\n\n' +
`${ EXPECTED_COLOR('expected') } value should be a string or a regular expression.\n` +
`${ EXPECTED_COLOR('expected') } value must be a string or a regular expression.\n` +
printWithType('Expected', expected, printExpected));

@@ -332,3 +392,6 @@

const pass = new RegExp(isString ? escapeStrForRegex(expected) : expected).
const pass = new RegExp(
typeof expected === 'string' ?
escapeStrForRegex(expected) :
expected).
test(received);

@@ -335,0 +398,0 @@ const message = pass ?

@@ -11,6 +11,8 @@ /**

'use strict';var _require =
'use strict';
const CALL_PRINT_LIMIT = 3;
const LAST_CALL_PRINT_LIMIT = 1;var _require =

@@ -20,48 +22,36 @@

require('jest-matcher-utils');const ensureNoExpected = _require.ensureNoExpected;const ensureExpectedIsNumber = _require.ensureExpectedIsNumber;const pluralize = _require.pluralize;
const spyMatchers = {
toHaveBeenCalled(actual, expected) {
ensureNoExpected(expected, 'toHaveBeenCalled');
ensureMockOrSpy(actual, 'toHaveBeenCalled');
return isSpy(actual) ?
jasmineToHaveBeenCalled(actual) :
jestToHaveBeenCalled(actual);
},
toBeCalled(actual, expected) {
ensureNoExpected(expected, 'toBeCalled');
ensureMockOrSpy(actual, 'toBeCalled');
return isSpy(actual) ?
jasmineToHaveBeenCalled(actual) :
jestToHaveBeenCalled(actual);
},
toHaveBeenCalledTimes(actual, expected) {
ensureExpectedIsNumber(expected, 'toHaveBeenCalledTimes');
ensureMockOrSpy(actual, 'toHaveBeenCalledTimes');
const actualIsSpy = isSpy(actual);
const type = actualIsSpy ? 'spy' : 'mock function';
const count = actualIsSpy ?
actual.calls.count() :
actual.mock.calls.length;
const pass = count === expected;
const message = pass ?
`Expected the ${ type } not to be called ${ pluralize('time', expected) }` +
`, but it was called ${ pluralize('time', count) }.` :
`Expected the ${ type } to be called ${ pluralize('time', expected) },` +
` but it was called ${ pluralize('time', count) }.`;
return { message, pass };
} };
require('jest-matcher-utils');const ensureExpectedIsNumber = _require.ensureExpectedIsNumber;const ensureNoExpected = _require.ensureNoExpected;const EXPECTED_COLOR = _require.EXPECTED_COLOR;const matcherHint = _require.matcherHint;const pluralize = _require.pluralize;const printExpected = _require.printExpected;const printReceived = _require.printReceived;const printWithType = _require.printWithType;const RECEIVED_COLOR = _require.RECEIVED_COLOR;
const RECEIVED_NAME = {
spy: 'spy',
'mock function': 'jest.fn()' };
const jestToHaveBeenCalled = actual => {
const pass = actual.mock.calls.length > 0;
const equals = global.jasmine.matchersUtil.equals;
const createToBeCalledMatcher = matcherName => (received, expected) => {
ensureNoExpected(expected, matcherName);
ensureMock(received, matcherName);
const receivedIsSpy = isSpy(received);
const type = receivedIsSpy ? 'spy' : 'mock function';
const count = receivedIsSpy ?
received.calls.count() :
received.mock.calls.length;
const calls = receivedIsSpy ?
received.calls.all().map(x => x.args) :
received.mock.calls;
const pass = count > 0;
const message = pass ?
`Expected the mock function not to be called, but it was` +
` called ${ pluralize('time', actual.mock.calls.length) }.` :
`Expected the mock function to be called.`;
matcherHint('.not' + matcherName, RECEIVED_NAME[type], '') + '\n\n' +
`Expected ${ type } not to be called ` +
formatReceivedCalls(calls, CALL_PRINT_LIMIT, { sameSentence: true }) :
matcherHint(matcherName, RECEIVED_NAME[type], '') + '\n\n' +
`Expected ${ type } to have been called.`;

@@ -71,8 +61,24 @@ return { message, pass };

const jasmineToHaveBeenCalled = actual => {
const pass = actual.calls.any();
const createToBeCalledWithMatcher = matcherName =>
function (
received)
{for (var _len = arguments.length, expected = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {expected[_key - 1] = arguments[_key];}
ensureMock(received, matcherName);
const receivedIsSpy = isSpy(received);
const type = receivedIsSpy ? 'spy' : 'mock function';
const calls = receivedIsSpy ?
received.calls.all().map(x => x.args) :
received.mock.calls;
const pass = calls.some(call => equals(call, expected));
const message = pass ?
`Expected the spy not to be called, but it was` +
` called ${ pluralize('time', actual.calls.count()) }.` :
`Expected the spy to be called.`;
matcherHint('.not' + matcherName, RECEIVED_NAME[type]) + '\n\n' +
`Expected ${ type } not to have been called with:\n` +
` ${ printExpected(expected) }` :
matcherHint(matcherName, RECEIVED_NAME[type]) + '\n\n' +
`Expected ${ type } to have been called with:\n` +
` ${ printExpected(expected) }\n` +
formatReceivedCalls(calls, CALL_PRINT_LIMIT);

@@ -82,6 +88,74 @@ return { message, pass };

const createLastCalledWithMatcher = matcherName =>
function (
received)
{for (var _len2 = arguments.length, expected = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {expected[_key2 - 1] = arguments[_key2];}
ensureMock(received, matcherName);
const receivedIsSpy = isSpy(received);
const type = receivedIsSpy ? 'spy' : 'mock function';
const calls = receivedIsSpy ?
received.calls.all().map(x => x.args) :
received.mock.calls;
const pass = equals(calls[calls.length - 1], expected);
const message = pass ?
matcherHint('.not' + matcherName, RECEIVED_NAME[type]) + '\n\n' +
`Expected ${ type } to not have been last called with:\n` +
` ${ printExpected(expected) }` :
matcherHint(matcherName, RECEIVED_NAME[type]) + '\n\n' +
`Expected ${ type } to have been last called with:\n` +
` ${ printExpected(expected) }\n` +
formatReceivedCalls(calls, LAST_CALL_PRINT_LIMIT, { isLast: true });
return { message, pass };
};
const spyMatchers = {
toBeCalled: createToBeCalledMatcher('.toBeCalled'),
toHaveBeenCalled: createToBeCalledMatcher('.toHaveBeenCalled'),
toBeCalledWith: createToBeCalledWithMatcher('.toBeCalledWith'),
toHaveBeenCalledWith: createToBeCalledWithMatcher('.toHaveBeenCalledWith'),
toHaveBeenLastCalledWith:
createLastCalledWithMatcher('.toHaveBeenLastCalledWith'),
lastCalledWith: createLastCalledWithMatcher('.lastCalledWith'),
toHaveBeenCalledTimes(received, expected) {
const matcherName = '.toHaveBeenCalledTimes';
ensureExpectedIsNumber(expected, matcherName);
ensureMock(received, matcherName);
const receivedIsSpy = isSpy(received);
const type = receivedIsSpy ? 'spy' : 'mock function';
const count = receivedIsSpy ?
received.calls.count() :
received.mock.calls.length;
const pass = count === expected;
const message = pass ?
matcherHint(
'.not' +
matcherName,
RECEIVED_NAME[type],
String(expected)) +
`\n\n` +
`Expected ${ type } not to be called ` +
`${ EXPECTED_COLOR(pluralize('time', expected)) }, but it was` +
` called exactly ${ RECEIVED_COLOR(pluralize('time', count)) }.` :
matcherHint(matcherName, RECEIVED_NAME[type], String(expected)) +
'\n\n' +
`Expected ${ type } to have been called ` +
`${ EXPECTED_COLOR(pluralize('time', expected)) },` +
` but it was called ${ RECEIVED_COLOR(pluralize('time', count)) }.`;
return { message, pass };
} };
const isSpy = spy => spy.calls && typeof spy.calls.count === 'function';
const ensureMockOrSpy = (mockOrSpy, matcherName) => {
const ensureMock = (mockOrSpy, matcherName) => {
if (
!mockOrSpy ||
(mockOrSpy.calls === undefined || mockOrSpy.calls.all === undefined) &&

@@ -91,3 +165,5 @@ mockOrSpy._isMockFunction !== true)

throw new Error(
`${ matcherName } matcher can only be used on a spy or mock function.`);
matcherHint('[.not]' + matcherName, 'jest.fn()', '') + '\n\n' +
`${ RECEIVED_COLOR('jest.fn()') } value must be a mock function or spy.\n` +
printWithType('Received', mockOrSpy, printReceived));

@@ -97,2 +173,25 @@ }

const formatReceivedCalls = (calls, limit, options) => {
if (calls.length) {
const but = options && options.sameSentence ? 'but' : 'But';
const count = calls.length - limit;
const printedCalls =
calls.
slice(-limit).
reverse().
map(printReceived).
join(', ');
return (
`${ but } it was ${ options && options.isLast ? 'last ' : '' }called ` +
`with:\n ` + printedCalls + (
count > 0 ?
'\nand ' + RECEIVED_COLOR(pluralize('more call', count)) + '.' :
''));
} else {
return `But it was ${ RECEIVED_COLOR('not called') }.`;
}
};
module.exports = spyMatchers;

@@ -31,3 +31,3 @@ /**

const createMatcher = name =>
const createMatcher = matcherName =>
(actual, expected) => {

@@ -48,7 +48,7 @@ const value = expected;

if (typeof expected === 'function') {
return toThrowMatchingError(name, error, expected);
return toThrowMatchingError(matcherName, error, expected);
} else if (expected instanceof RegExp) {
return toThrowMatchingStringOrRegexp(name, error, expected, value);
return toThrowMatchingStringOrRegexp(matcherName, error, expected, value);
} else if (expected && typeof expected === 'object') {
return toThrowMatchingErrorInstance(name, error, expected);
return toThrowMatchingErrorInstance(matcherName, error, expected);
} else if (expected === undefined) {

@@ -59,6 +59,6 @@ const pass = error !== undefined;

message: pass ?
() => matcherHint('.not.' + name, 'function', '') + '\n\n' +
() => matcherHint('.not' + matcherName, 'function', '') + '\n\n' +
'Expected the function not to throw an error.\n' +
printActualErrorMessage(error) :
() => matcherHint('.' + name, 'function', getType(value)) + '\n\n' +
() => matcherHint(matcherName, 'function', getType(value)) + '\n\n' +
'Expected the function to throw an error.\n' +

@@ -69,6 +69,6 @@ printActualErrorMessage(error) };

throw new Error(
matcherHint('.not.' + name, 'function', getType(value)) + '\n\n' +
matcherHint('.not' + matcherName, 'function', getType(value)) + '\n\n' +
'Unexpected argument passed.\nExpected: ' +
`${ printExpected('string') }, ${ printExpected('Error (type)') } or ${ printExpected('regexp') }.\n` +
printWithType('Got', expected, printExpected));
printWithType('Got', String(expected), printExpected));

@@ -79,4 +79,4 @@ }

const matchers = {
toThrow: createMatcher('toThrow'),
toThrowError: createMatcher('toThrowError') };
toThrow: createMatcher('.toThrow'),
toThrowError: createMatcher('.toThrowError') };

@@ -96,7 +96,7 @@

const message = pass ?
() => matcherHint('.not.' + name, 'function', getType(value)) + '\n\n' +
() => matcherHint('.not' + name, 'function', getType(value)) + '\n\n' +
`Expected the function not to throw an error matching:\n` +
` ${ printExpected(value) }\n` +
printActualErrorMessage(error) :
() => matcherHint('.' + name, 'function', getType(value)) + '\n\n' +
() => matcherHint(name, 'function', getType(value)) + '\n\n' +
`Expected the function to throw an error matching:\n` +

@@ -120,7 +120,7 @@ ` ${ printExpected(value) }\n` +

const message = pass ?
() => matcherHint('.not.' + name, 'function', 'error') + '\n\n' +
() => matcherHint('.not' + name, 'function', 'error') + '\n\n' +
`Expected the function not to throw an error matching:\n` +
` ${ printExpected(expectedError) }\n` +
printActualErrorMessage(error) :
() => matcherHint('.' + name, 'function', 'error') + '\n\n' +
() => matcherHint(name, 'function', 'error') + '\n\n' +
`Expected the function to throw an error matching:\n` +

@@ -140,7 +140,7 @@ ` ${ printExpected(expectedError) }\n` +

const message = pass ?
() => matcherHint('.not.' + name, 'function', 'type') + '\n\n' +
() => matcherHint('.not' + name, 'function', 'type') + '\n\n' +
`Expected the function not to throw an error of type:\n` +
` ${ printExpected(ErrorClass.name) }\n` +
printActualErrorMessage(error) :
() => matcherHint('.' + name, 'function', 'type') + '\n\n' +
() => matcherHint(name, 'function', 'type') + '\n\n' +
`Expected the function to throw an error of type:\n` +

@@ -159,5 +159,9 @@ ` ${ printExpected(ErrorClass.name) }\n` +

RECEIVED_COLOR(
' ' + message + formatStackTrace(stack, { rootDir: process.cwd() })));
' ' + message + formatStackTrace(stack, {
noStackTrace: false,
rootDir: process.cwd(),
testRegex: '' })));
}

@@ -164,0 +168,0 @@

{
"name": "jest-matchers",
"version": "15.1.1",
"version": "15.2.0-alpha.c681f819",
"repository": {

@@ -11,9 +11,6 @@ "type": "git",

"dependencies": {
"jest-diff": "^15.1.0",
"jest-matcher-utils": "^15.1.0",
"jest-util": "^15.1.1"
"jest-diff": "^15.2.0-alpha.c681f819",
"jest-matcher-utils": "^15.2.0-alpha.c681f819",
"jest-util": "^15.2.0-alpha.c681f819"
},
"devDependencies": {
"strip-ansi": "^3.0.1"
},
"scripts": {

@@ -20,0 +17,0 @@ "test": "../../packages/jest-cli/bin/jest.js"

SocketSocket SOC 2 Logo

Product

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

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc