How to use fnNameFor method in Jest

Best JavaScript code snippet using jest

Run Jest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

AsymmetricMatcher-test.js

Source: AsymmetricMatcher-test.js Github

copy
1/**
2 * Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
3 *
4 * This source code is licensed under the BSD-style license found in the
5 * LICENSE file in the root directory of this source tree. An additional grant
6 * of patent rights can be found in the PATENTS file in the same directory.
7 */
8
9/* eslint-disable max-len */
10
11'use strict';
12
13const prettyFormat = require('../');
14const AsymmetricMatcher = require('../plugins/AsymmetricMatcher');
15let options;
16
17function fnNameFor(func) {
18  if (func.name) {
19    return func.name;
20  }
21
22  const matches = func.toString().match(/^\s*function\s*(\w*)\s*\(/);
23  return matches ? matches[1] : '<anonymous>';
24}
25
26beforeEach(() => {
27  options = {plugins: [AsymmetricMatcher]};
28});
29
30[
31  String,
32  Function,
33  Array,
34  Object,
35  RegExp,
36  Symbol,
37  Function,
38  () => {},
39  function namedFuntction() {},
40].forEach(type => {
41  test(`supports any(${fnNameFor(type)})`, () => {
42    const result = prettyFormat(expect.any(type), options);
43    expect(result).toEqual(`Any<${fnNameFor(type)}>`);
44  });
45
46  test(`supports nested any(${fnNameFor(type)})`, () => {
47    const result = prettyFormat(
48      {
49        test: {
50          nested: expect.any(type),
51        },
52      },
53      options,
54    );
55    expect(result).toEqual(
56      `Object {\n  "test": Object {\n    "nested": Any<${fnNameFor(type)}>,\n  },\n}`,
57    );
58  });
59});
60
61test(`anything()`, () => {
62  const result = prettyFormat(expect.anything(), options);
63  expect(result).toEqual('Anything');
64});
65
66test(`arrayContaining()`, () => {
67  const result = prettyFormat(expect.arrayContaining([1, 2]), options);
68  expect(result).toEqual(
69    `ArrayContaining [
70  1,
71  2,
72]`,
73  );
74});
75
76test(`objectContaining()`, () => {
77  const result = prettyFormat(expect.objectContaining({a: 'test'}), options);
78  expect(result).toEqual(
79    `ObjectContaining {
80  "a": "test",
81}`,
82  );
83});
84
85test(`stringContaining(string)`, () => {
86  const result = prettyFormat(expect.stringContaining('jest'), options);
87  expect(result).toEqual(`StringContaining "jest"`);
88});
89
90test(`stringMatching(string)`, () => {
91  const result = prettyFormat(expect.stringMatching('jest'), options);
92  expect(result).toEqual('StringMatching /jest/');
93});
94
95test(`stringMatching(regexp)`, () => {
96  const result = prettyFormat(expect.stringMatching(/(jest|niema).*/), options);
97  expect(result).toEqual('StringMatching /(jest|niema).*/');
98});
99
100test(`supports multiple nested asymmetric matchers`, () => {
101  const result = prettyFormat(
102    {
103      test: {
104        nested: expect.objectContaining({
105          a: expect.arrayContaining([1]),
106          b: expect.anything(),
107          c: expect.any(String),
108          d: expect.stringContaining('jest'),
109          e: expect.stringMatching('jest'),
110          f: expect.objectContaining({test: 'case'}),
111        }),
112      },
113    },
114    options,
115  );
116  expect(result).toEqual(
117    `Object {
118  "test": Object {
119    "nested": ObjectContaining {
120      "a": ArrayContaining [
121        1,
122      ],
123      "b": Anything,
124      "c": Any<String>,
125      "d": StringContaining "jest",
126      "e": StringMatching /jest/,
127      "f": ObjectContaining {
128        "test": "case",
129      },
130    },
131  },
132}`,
133  );
134});
135
136test(`supports minified output`, () => {
137  options.min = true;
138  const result = prettyFormat(
139    {
140      test: {
141        nested: expect.objectContaining({
142          a: expect.arrayContaining([1]),
143          b: expect.anything(),
144          c: expect.any(String),
145          d: expect.stringContaining('jest'),
146          e: expect.stringMatching('jest'),
147          f: expect.objectContaining({test: 'case'}),
148        }),
149      },
150    },
151    options,
152  );
153  expect(result).toEqual(
154    `{"test": {"nested": ObjectContaining {"a": ArrayContaining [1], "b": Anything, "c": Any<String>, "d": StringContaining "jest", "e": StringMatching /jest/, "f": ObjectContaining {"test": "case"}}}}`,
155  );
156});
157
Full Screen

toThrowError.js

Source: toThrowError.js Github

copy
1getJasmineRequireObj().toThrowError = function(j$) {
2  function toThrowError (util) {
3    return {
4      compare: function(actual) {
5        var threw = false,
6          thrown,
7          errorType,
8          message,
9          regexp,
10          name,
11          constructorName;
12
13        if (typeof actual != "function") {
14          throw new Error("Actual is not a Function");
15        }
16
17        extractExpectedParams.apply(null, arguments);
18
19        try {
20          actual();
21        } catch (e) {
22          threw = true;
23          thrown = e;
24        }
25
26        if (!threw) {
27          return fail("Expected function to throw an Error.");
28        }
29
30        if (!(thrown instanceof Error)) {
31          return fail("Expected function to throw an Error, but it threw " + thrown + ".");
32        }
33
34        if (arguments.length == 1) {
35          return pass("Expected function not to throw an Error, but it threw " + fnNameFor(thrown) + ".");
36        }
37
38        if (errorType) {
39          name = fnNameFor(errorType);
40          constructorName = fnNameFor(thrown.constructor);
41        }
42
43        if (errorType && message) {
44          if (thrown.constructor == errorType && util.equals(thrown.message, message)) {
45            return pass("Expected function not to throw " + name + " with message \"" + message + "\".");
46          } else {
47            return fail("Expected function to throw " + name + " with message \"" + message +
48                        "\", but it threw " + constructorName + " with message \"" + thrown.message + "\".");
49          }
50        }
51
52        if (errorType && regexp) {
53          if (thrown.constructor == errorType && regexp.test(thrown.message)) {
54            return pass("Expected function not to throw " + name + " with message matching " + regexp + ".");
55          } else {
56            return fail("Expected function to throw " + name + " with message matching " + regexp +
57                        ", but it threw " + constructorName + " with message \"" + thrown.message + "\".");
58          }
59        }
60
61        if (errorType) {
62          if (thrown.constructor == errorType) {
63            return pass("Expected function not to throw " + name + ".");
64          } else {
65            return fail("Expected function to throw " + name + ", but it threw " + constructorName + ".");
66          }
67        }
68
69        if (message) {
70          if (thrown.message == message) {
71            return pass("Expected function not to throw an exception with message " + j$.pp(message) + ".");
72          } else {
73            return fail("Expected function to throw an exception with message " + j$.pp(message) +
74                        ", but it threw an exception with message " + j$.pp(thrown.message) + ".");
75          }
76        }
77
78        if (regexp) {
79          if (regexp.test(thrown.message)) {
80            return pass("Expected function not to throw an exception with a message matching " + j$.pp(regexp) + ".");
81          } else {
82            return fail("Expected function to throw an exception with a message matching " + j$.pp(regexp) +
83                        ", but it threw an exception with message " + j$.pp(thrown.message) + ".");
84          }
85        }
86
87        function fnNameFor(func) {
88            return func.name || func.toString().match(/^\s*function\s*(\w*)\s*\(/)[1];
89        }
90
91        function pass(notMessage) {
92          return {
93            pass: true,
94            message: notMessage
95          };
96        }
97
98        function fail(message) {
99          return {
100            pass: false,
101            message: message
102          };
103        }
104
105        function extractExpectedParams() {
106          if (arguments.length == 1) {
107            return;
108          }
109
110          if (arguments.length == 2) {
111            var expected = arguments[1];
112
113            if (expected instanceof RegExp) {
114              regexp = expected;
115            } else if (typeof expected == "string") {
116              message = expected;
117            } else if (checkForAnErrorType(expected)) {
118              errorType = expected;
119            }
120
121            if (!(errorType || message || regexp)) {
122              throw new Error("Expected is not an Error, string, or RegExp.");
123            }
124          } else {
125            if (checkForAnErrorType(arguments[1])) {
126              errorType = arguments[1];
127            } else {
128              throw new Error("Expected error type is not an Error.");
129            }
130
131            if (arguments[2] instanceof RegExp) {
132              regexp = arguments[2];
133            } else if (typeof arguments[2] == "string") {
134              message = arguments[2];
135            } else {
136              throw new Error("Expected error message is not a string or RegExp.");
137            }
138          }
139        }
140
141        function checkForAnErrorType(type) {
142          if (typeof type !== "function") {
143            return false;
144          }
145
146          var Surrogate = function() {};
147          Surrogate.prototype = type.prototype;
148          return (new Surrogate()) instanceof Error;
149        }
150      }
151    };
152  }
153
154  return toThrowError;
155};
156
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Jest on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)