123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415 |
- 'use strict';
- var _jestMatcherUtils = require('jest-matcher-utils');
- var matcherUtils = _interopRequireWildcard(_jestMatcherUtils);
- var _utils = require('./utils');
- var _matchers = require('./matchers');
- var _matchers2 = _interopRequireDefault(_matchers);
- var _spy_matchers = require('./spy_matchers');
- var _spy_matchers2 = _interopRequireDefault(_spy_matchers);
- var _to_throw_matchers = require('./to_throw_matchers');
- var _to_throw_matchers2 = _interopRequireDefault(_to_throw_matchers);
- var _jasmine_utils = require('./jasmine_utils');
- var _asymmetric_matchers = require('./asymmetric_matchers');
- var _jest_matchers_object = require('./jest_matchers_object');
- var _extract_expected_assertions_errors = require('./extract_expected_assertions_errors');
- var _extract_expected_assertions_errors2 = _interopRequireDefault(
- _extract_expected_assertions_errors
- );
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : {default: obj};
- }
- function _interopRequireWildcard(obj) {
- if (obj && obj.__esModule) {
- return obj;
- } else {
- var newObj = {};
- if (obj != null) {
- for (var key in obj) {
- if (Object.prototype.hasOwnProperty.call(obj, key))
- newObj[key] = obj[key];
- }
- }
- newObj.default = obj;
- return newObj;
- }
- }
- /**
- * Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- class JestAssertionError extends Error {}
- const isPromise = obj =>
- !!obj &&
- (typeof obj === 'object' || typeof obj === 'function') &&
- typeof obj.then === 'function';
- const createToThrowErrorMatchingSnapshotMatcher = function(matcher) {
- return function(received, testNameOrInlineSnapshot) {
- return matcher.apply(this, [received, testNameOrInlineSnapshot, true]);
- };
- };
- const getPromiseMatcher = (name, matcher) => {
- if (name === 'toThrow' || name === 'toThrowError') {
- return (0, _to_throw_matchers.createMatcher)('.' + name, true);
- } else if (
- name === 'toThrowErrorMatchingSnapshot' ||
- name === 'toThrowErrorMatchingInlineSnapshot'
- ) {
- return createToThrowErrorMatchingSnapshotMatcher(matcher);
- }
- return null;
- };
- const expect = function(actual) {
- if ((arguments.length <= 1 ? 0 : arguments.length - 1) !== 0) {
- throw new Error('Expect takes at most one argument.');
- }
- const allMatchers = (0, _jest_matchers_object.getMatchers)();
- const expectation = {
- not: {},
- rejects: {not: {}},
- resolves: {not: {}}
- };
- const err = new JestAssertionError();
- Object.keys(allMatchers).forEach(name => {
- const matcher = allMatchers[name];
- const promiseMatcher = getPromiseMatcher(name, matcher) || matcher;
- expectation[name] = makeThrowingMatcher(matcher, false, actual);
- expectation.not[name] = makeThrowingMatcher(matcher, true, actual);
- expectation.resolves[name] = makeResolveMatcher(
- name,
- promiseMatcher,
- false,
- actual,
- err
- );
- expectation.resolves.not[name] = makeResolveMatcher(
- name,
- promiseMatcher,
- true,
- actual,
- err
- );
- expectation.rejects[name] = makeRejectMatcher(
- name,
- promiseMatcher,
- false,
- actual,
- err
- );
- expectation.rejects.not[name] = makeRejectMatcher(
- name,
- promiseMatcher,
- true,
- actual,
- err
- );
- });
- return expectation;
- };
- const getMessage = message =>
- (message && message()) ||
- matcherUtils.RECEIVED_COLOR('No message was specified for this matcher.');
- const makeResolveMatcher = (matcherName, matcher, isNot, actual, outerErr) =>
- function() {
- for (
- var _len = arguments.length, args = Array(_len), _key = 0;
- _key < _len;
- _key++
- ) {
- args[_key] = arguments[_key];
- }
- const matcherStatement = `.resolves.${isNot ? 'not.' : ''}${matcherName}`;
- if (!isPromise(actual)) {
- throw new JestAssertionError(
- matcherUtils.matcherHint(matcherStatement, 'received', '') +
- '\n\n' +
- `${matcherUtils.RECEIVED_COLOR(
- 'received'
- )} value must be a Promise.\n` +
- matcherUtils.printWithType(
- 'Received',
- actual,
- matcherUtils.printReceived
- )
- );
- }
- const innerErr = new JestAssertionError();
- return actual.then(
- result =>
- makeThrowingMatcher(matcher, isNot, result, innerErr).apply(null, args),
- reason => {
- outerErr.message =
- matcherUtils.matcherHint(matcherStatement, 'received', '') +
- '\n\n' +
- `Expected ${matcherUtils.RECEIVED_COLOR(
- 'received'
- )} Promise to resolve, ` +
- 'instead it rejected to value\n' +
- ` ${matcherUtils.printReceived(reason)}`;
- return Promise.reject(outerErr);
- }
- );
- };
- const makeRejectMatcher = (matcherName, matcher, isNot, actual, outerErr) =>
- function() {
- for (
- var _len2 = arguments.length, args = Array(_len2), _key2 = 0;
- _key2 < _len2;
- _key2++
- ) {
- args[_key2] = arguments[_key2];
- }
- const matcherStatement = `.rejects.${isNot ? 'not.' : ''}${matcherName}`;
- if (!isPromise(actual)) {
- throw new JestAssertionError(
- matcherUtils.matcherHint(matcherStatement, 'received', '') +
- '\n\n' +
- `${matcherUtils.RECEIVED_COLOR(
- 'received'
- )} value must be a Promise.\n` +
- matcherUtils.printWithType(
- 'Received',
- actual,
- matcherUtils.printReceived
- )
- );
- }
- const innerErr = new JestAssertionError();
- return actual.then(
- result => {
- outerErr.message =
- matcherUtils.matcherHint(matcherStatement, 'received', '') +
- '\n\n' +
- `Expected ${matcherUtils.RECEIVED_COLOR(
- 'received'
- )} Promise to reject, ` +
- 'instead it resolved to value\n' +
- ` ${matcherUtils.printReceived(result)}`;
- return Promise.reject(outerErr);
- },
- reason =>
- makeThrowingMatcher(matcher, isNot, reason, innerErr).apply(null, args)
- );
- };
- const makeThrowingMatcher = (matcher, isNot, actual, err) =>
- function throwingMatcher() {
- let throws = true;
- const utils = Object.assign({}, matcherUtils, {
- iterableEquality: _utils.iterableEquality,
- subsetEquality: _utils.subsetEquality
- });
- 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)},
- (0, _jest_matchers_object.getState)(),
- {
- equals: _jasmine_utils.equals,
- error: err,
- isNot: isNot,
- utils: utils
- }
- );
- const processResult = result => {
- _validateResult(result);
- (0, _jest_matchers_object.getState)().assertionCalls++;
- if ((result.pass && isNot) || (!result.pass && !isNot)) {
- // XOR
- const message = getMessage(result.message);
- let error;
- if (err) {
- error = err;
- error.message = message;
- } else {
- error = new JestAssertionError(message);
- // Try to remove this function from the stack trace frame.
- // Guard for some environments (browsers) that do not support this feature.
- if (Error.captureStackTrace) {
- Error.captureStackTrace(error, throwingMatcher);
- }
- }
- // Passing the result of the matcher with the error so that a custom
- // reporter could access the actual and expected objects of the result
- // for example in order to display a custom visual diff
- error.matcherResult = result;
- if (throws) {
- throw error;
- } else {
- (0, _jest_matchers_object.getState)().suppressedErrors.push(error);
- }
- }
- };
- const handlError = error => {
- if (
- matcher[_jest_matchers_object.INTERNAL_MATCHER_FLAG] === true &&
- !(error instanceof JestAssertionError) &&
- error.name !== 'PrettyFormatPluginError' &&
- // Guard for some environments (browsers) that do not support this feature.
- Error.captureStackTrace
- ) {
- // Try to remove this and deeper functions from the stack trace frame.
- Error.captureStackTrace(error, throwingMatcher);
- }
- throw error;
- };
- let potentialResult;
- try {
- for (
- var _len3 = arguments.length, args = Array(_len3), _key3 = 0;
- _key3 < _len3;
- _key3++
- ) {
- args[_key3] = arguments[_key3];
- }
- potentialResult = matcher.apply(matcherContext, [actual].concat(args));
- if (isPromise(potentialResult)) {
- const asyncResult = potentialResult;
- return asyncResult
- .then(aResult => processResult(aResult))
- .catch(error => handlError(error));
- } else {
- const syncResult = potentialResult;
- return processResult(syncResult);
- }
- } catch (error) {
- return handlError(error);
- }
- };
- expect.extend = matchers =>
- (0, _jest_matchers_object.setMatchers)(matchers, false, expect);
- expect.anything = _asymmetric_matchers.anything;
- expect.any = _asymmetric_matchers.any;
- expect.not = {
- arrayContaining: _asymmetric_matchers.arrayNotContaining,
- objectContaining: _asymmetric_matchers.objectNotContaining,
- stringContaining: _asymmetric_matchers.stringNotContaining,
- stringMatching: _asymmetric_matchers.stringNotMatching
- };
- expect.objectContaining = _asymmetric_matchers.objectContaining;
- expect.arrayContaining = _asymmetric_matchers.arrayContaining;
- expect.stringContaining = _asymmetric_matchers.stringContaining;
- expect.stringMatching = _asymmetric_matchers.stringMatching;
- const _validateResult = result => {
- if (
- typeof result !== 'object' ||
- typeof result.pass !== 'boolean' ||
- (result.message &&
- typeof result.message !== 'string' &&
- typeof result.message !== 'function')
- ) {
- throw new Error(
- 'Unexpected return from a matcher function.\n' +
- 'Matcher functions should ' +
- 'return an object in the following format:\n' +
- ' {message?: string | function, pass: boolean}\n' +
- `'${matcherUtils.stringify(result)}' was returned`
- );
- }
- };
- function assertions(expected) {
- const error = new Error();
- if (Error.captureStackTrace) {
- Error.captureStackTrace(error, assertions);
- }
- (0, _jest_matchers_object.getState)().expectedAssertionsNumber = expected;
- (0, _jest_matchers_object.getState)().expectedAssertionsNumberError = error;
- }
- function hasAssertions() {
- const error = new Error();
- if (Error.captureStackTrace) {
- Error.captureStackTrace(error, hasAssertions);
- }
- matcherUtils.ensureNoExpected(
- arguments.length <= 0 ? undefined : arguments[0],
- '.hasAssertions'
- );
- (0, _jest_matchers_object.getState)().isExpectingAssertions = true;
- (0, _jest_matchers_object.getState)().isExpectingAssertionsError = error;
- }
- // add default jest matchers
- (0, _jest_matchers_object.setMatchers)(_matchers2.default, true, expect);
- (0, _jest_matchers_object.setMatchers)(_spy_matchers2.default, true, expect);
- (0, _jest_matchers_object.setMatchers)(
- _to_throw_matchers2.default,
- true,
- expect
- );
- expect.addSnapshotSerializer = () => void 0;
- expect.assertions = assertions;
- expect.hasAssertions = hasAssertions;
- expect.getState = _jest_matchers_object.getState;
- expect.setState = _jest_matchers_object.setState;
- expect.extractExpectedAssertionsErrors =
- _extract_expected_assertions_errors2.default;
- module.exports = expect;
|