UNPKG

2.64 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.default = void 0;
7
8class JestAssertionError extends Error {
9 constructor(result, callsite) {
10 super(typeof result.message === 'function' ? result.message() : result.message);
11 this.matcherResult = result;
12
13 if (Error.captureStackTrace) {
14 Error.captureStackTrace(this, callsite);
15 }
16 }
17
18}
19
20const wrapMatcher = (matcher, customMessage, config) => {
21 const newMatcher = (...args) => {
22 try {
23 return matcher(...args);
24 } catch (error) {
25 if (!error.matcherResult) {
26 throw error;
27 }
28
29 const {
30 matcherResult
31 } = error;
32
33 if (typeof customMessage !== 'string' || customMessage.length < 1) {
34 throw new JestAssertionError(matcherResult, newMatcher);
35 }
36
37 const matcherMessage = typeof error.matcherResult.message === 'function' ? error.matcherResult.message() : error.matcherResult.message;
38 const messagePrefix = config.showPrefix ? 'Custom message:\n ' : '';
39
40 const message = () => messagePrefix + customMessage + (config.showMatcherMessage ? '\n\n' + matcherMessage : '');
41
42 throw new JestAssertionError({ ...matcherResult,
43 message
44 }, newMatcher);
45 }
46 };
47
48 return newMatcher;
49};
50
51const wrapMatchers = (matchers, customMessage, config) => {
52 return Object.keys(matchers).reduce((acc, name) => {
53 const matcher = matchers[name];
54
55 if (typeof matcher === 'function') {
56 acc[name] = wrapMatcher(matcher, customMessage, config);
57 } else {
58 acc[name] = wrapMatchers(matcher, customMessage, config); // recurse on .not/.resolves/.rejects
59 }
60
61 return acc;
62 }, {});
63};
64
65var _default = expect => {
66 // proxy the expect function
67 let expectProxy = Object.assign((actual, customMessage, options = {}) => {
68 const config = {
69 showMatcherMessage: typeof options.showMatcherMessage === 'boolean' ? options.showMatcherMessage : true,
70 showPrefix: typeof options.showPrefix === 'boolean' ? options.showPrefix : true
71 };
72 let matchers = expect(actual); // partially apply expect to get all matchers and chain them
73
74 if (customMessage) {
75 // only pay the cost of proxying matchers if we received a customMessage
76 matchers = wrapMatchers(matchers, customMessage, config);
77 }
78
79 return matchers;
80 }, expect // clone additional properties on expect
81 );
82
83 expectProxy.extend = o => {
84 expect.extend(o); // add new matchers to expect
85
86 expectProxy = Object.assign(expectProxy, expect); // clone new asymmetric matchers
87 };
88
89 return expectProxy;
90};
91
92exports.default = _default;
\No newline at end of file