├── .babelrc
├── .gitignore
├── .travis.yml
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── bin
├── es5
│ ├── AssertJS
│ │ ├── Assert.js
│ │ ├── InvalidValueException.js
│ │ ├── MessageFactory.js
│ │ └── ValueConverter.js
│ ├── assert-js.js
│ └── assert-js.min.js
└── es6
│ └── assert-js.js
├── package.json
├── src
└── AssertJS
│ ├── Assert.js
│ ├── InvalidValueException.js
│ ├── MessageFactory.js
│ └── ValueConverter.js
├── tests
└── AssertJS
│ ├── AssertTest.js
│ ├── MessageFactoryTest.js
│ └── ValueConverterTest.js
└── webpack.config.js
/.babelrc:
--------------------------------------------------------------------------------
1 | { "presets": ["@babel/env"] }
2 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /node_modules/
2 | *.log
3 | package-lock.json
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | sudo: false
2 | language: node_js
3 | node_js:
4 | - "8"
5 | - "10"
6 | - "12"
7 |
8 | script:
9 | - npm test
10 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing guide
2 |
3 | ## Prepare Repository
4 |
5 | Before you start fork this project using [Github](https://help.github.com/articles/fork-a-repo/).
6 |
7 | ### 1. Clone your fork to your local machine
8 |
9 | ```
10 | mkdir Tiliqua
11 | cd Tiliqua
12 | git clone git@github.com:USERNAME/assert-js.git
13 | cd assert-js
14 | ```
15 |
16 | ### 2. Setup upstream repository
17 |
18 | ```
19 | git remote add upstream git@github.com:Tiliqua/assert-js.git
20 | ```
21 |
22 | ### 3. Check that the current tests pass
23 |
24 | > Before your start make sure [npm](https://www.npmjs.com/) is installed on your local machine
25 |
26 | ```
27 | npm install
28 | npm test
29 | ```
30 |
31 | ## Work on new feature/patch/bugfix
32 |
33 | ### 1. Make sure your master is up to date with upstream
34 |
35 | ```
36 | cd Tiliqua/assert-js
37 | git checkout master
38 | git pull upstream master
39 | ```
40 |
41 | ### 2. Create new branch
42 |
43 | ```
44 | git checkout -b BRANCH_NAME master
45 | ```
46 |
47 | ### 3. Work on your code
48 |
49 | Try to cover new code with unit tests.
50 | Try to keep your code as clean as possible.
51 |
52 | ### 4. Build changes before committing
53 |
54 | > Because AssertJS is written in ES6 that is not supported in 100% yet you need to build
55 | > project before committing to make it usable in all environments.
56 |
57 | ```
58 | npm run build
59 | ```
60 |
61 | ### 5. Commit your changes
62 |
63 | ```
64 | git commit -a -m "Put changes description here"
65 | ```
66 |
67 | ### 6. Push changes to your Github fork
68 |
69 | ```
70 | git push origin BRANCH_NAME
71 | ```
72 |
73 | ### 7. Open pull request using Github.
74 |
75 | All PR should be made from your fork repo BRANCH_NAME to upstream master branch.
76 |
77 | ## Update documentation
78 |
79 | In order to update documentation you need to checkout to ``gh-pages`` branch first
80 |
81 | ```
82 | git fetch upstream
83 | git checkout gh-pages
84 | ```
85 |
86 | Now you should follow instructions from "Work on new feature/patch/bugfix" section of this document.
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright (c) 2016 Norbert Orzechowicz
2 |
3 | Permission is hereby granted, free of charge, to any person
4 | obtaining a copy of this software and associated documentation
5 | files (the "Software"), to deal in the Software without
6 | restriction, including without limitation the rights to use,
7 | copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | copies of the Software, and to permit persons to whom the
9 | Software is furnished to do so, subject to the following
10 | conditions:
11 |
12 | The above copyright notice and this permission notice shall be
13 | included in all copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
17 | OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
19 | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
20 | WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 | FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22 | OTHER DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # AssertJS
2 |
3 | Javascript, battle tested, simple assertion library with no dependencies.
4 |
5 | Status:
6 |
7 | 
8 | 
9 | [](https://travis-ci.org/Tiliqua/assert-js)
10 | 
11 | 
12 |
13 | Example:
14 |
15 | ```js
16 | /**
17 | * @param {HTMLElement} element
18 | */
19 | function doSomethingWithHtmlElement(element)
20 | {
21 | Assert.instanceOf(element, HTMLElement);
22 |
23 | // do your job
24 | }
25 | ```
26 |
27 | Now you are covered by the Assertion, and you don't need to be worried that someone might pass empty object {} to doSomethingWithHtmlElement.
28 | `doSomethingWithHtmlElement` function was designed to accept only HTMLElement, nothing more!
29 |
30 | ## Usage
31 |
32 | ```
33 | npm install assert-js --save
34 | ```
35 |
36 | ```js
37 | let Assert = require('assert-js')
38 |
39 | Assert.true(true);
40 | Assert.false(false);
41 | Assert.instanceOf(new String("test"), String);
42 | Assert.instanceOneOf(new String("test"), [String, Number]);
43 | Assert.containsOnly([new String("test"), new String("test")],String);
44 | Assert.containsOnlyString(["test", "test1"]);
45 | Assert.containsOnlyInteger([1, 2]);
46 | Assert.containsOnlyNumber([2, 10.25]);
47 | Assert.integer(1);
48 | Assert.number(0.5);
49 | Assert.oddNumber(3);
50 | Assert.evenNumber(4);
51 | Assert.greaterThan(1, 10);
52 | Assert.greaterThanOrEqual(1, 1);
53 | Assert.lessThan(10, 5);
54 | Assert.lessThanOrEqual(1, 1);
55 | Assert.string("string");
56 | Assert.boolean(true);
57 | Assert.equal(1, 1);
58 | Assert.objectEqual({"key":"value"}, {"key":"value"});
59 | Assert.object({id: 1});
60 | Assert.hasFunction("testFunction", {testFunction: () => { alert('test'); } });
61 | Assert.hasProperty("test", {test: 'value'});
62 | Assert.isFunction(() => { alert('test'); });
63 | Assert.array([1, 2, 3, 4, 5]);
64 | Assert.count(0, []);
65 | Assert.notEmpty(0, [1, 2, 3]);
66 | Assert.jsonString('{"key": "value"}');
67 | Assert.email('norbert@orzechowicz.pl');
68 | Assert.url('https://github.com/Tiliqua/assert-js');
69 | Assert.uuid('3e9009a0-4b2f-414e-bf02-ec0df56fc864');
70 | Assert.hasElement('#div', window.document);
71 | Assert.hasAttribute('data-test', window.document.querySelector('#test'));
72 | Assert.hasAttributes(['data-test', 'id'], window.document.querySelector('#test'));
73 | Assert.throws(() => { throw new Error('some relevant error message'); }, new Error('some relevant error message'));
74 | ```
75 |
76 | ---
77 |
78 | ```js
79 | Assert.true(true);
80 | ```
81 |
82 | Asserts that expression or value is equal to **true**.
83 |
84 | Example:
85 |
86 | ```js
87 | Assert.true(1 === 2); // this will throw an Error.
88 | let falseValue = false;
89 | Assert.true(falseValue); // this will throw an Error.
90 | ```
91 |
92 | ---
93 |
94 |
95 | ```js
96 | Assert.false(false);
97 | ```
98 |
99 | Asserts that expression or value is equal to **false**.
100 |
101 | Example:
102 |
103 | ```js
104 | Assert.false(1 !== 2); // this will throw an Error.
105 | let falseValue = true;
106 | Assert.false(falseValue); // this will throw an Error.
107 | ```
108 |
109 | ---
110 |
111 | ```js
112 | Assert.instanceOf(new String("test"), String);
113 | ```
114 |
115 | Asserts that value is an instance of specific class.
116 |
117 | Example:
118 |
119 | ```js
120 | let div = window.document.querySelector('#my-div');
121 | Assert.instanceOf(element, HTMLDivElement);
122 | ```
123 |
124 | ---
125 |
126 | ```js
127 | Assert.instanceOneOf(new String("test"), [String, Number]);
128 | ```
129 |
130 | Asserts that value is an instance of at least one specific class.
131 |
132 | Example:
133 |
134 | ```js
135 | let div = window.document.querySelector('#my-div');
136 | Assert.instanceOneOf(element, [HTMLDivElement, HTMLElement]);
137 | ```
138 |
139 | ---
140 |
141 | ```js
142 | Assert.containsOnly([new String("test"), new String("test")],String);
143 | ```
144 |
145 | Asserts that array contains only instances of specific class.
146 |
147 | ---
148 |
149 | ```js
150 | Assert.containsOnlyString(["test", "test1"]);
151 | ```
152 |
153 | Asserts that array contains only strings.
154 |
155 | ---
156 |
157 | ```js
158 | Assert.containsOnlyInteger([1, 2]);
159 | ```
160 |
161 | Asserts that array contains only integers.
162 |
163 | ---
164 |
165 | ```js
166 | Assert.containsOnlyNumber([2, 10.25]);
167 | ```
168 |
169 | Asserts that array contains only numbers.
170 |
171 | ---
172 |
173 | ```js
174 | Assert.integer(1);
175 | ```
176 |
177 | Asserts that value is valid integer.
178 |
179 | ---
180 |
181 | ```js
182 | Assert.number(0.5);
183 | ```
184 |
185 | Asserts that value is valid number (integer, float).
186 |
187 | ---
188 |
189 | ```js
190 | Assert.oddNumber(3);
191 | ```
192 |
193 | Asserts that value is odd number.
194 |
195 | ---
196 |
197 | ```js
198 | Assert.evenNumber(4);
199 | ```
200 |
201 | Asserts that value is event number.
202 |
203 | ---
204 |
205 | ```js
206 | Assert.greaterThan(1, 10)
207 | ```
208 |
209 | Asserts that number is greater than.
210 |
211 | ---
212 |
213 | ```js
214 | Assert.greaterThanOrEqual(1, 1)
215 | ```
216 |
217 | Asserts that number is greater than or equal.
218 |
219 | ---
220 |
221 | ```js
222 | Assert.lessThan(10, 5)
223 | ```
224 |
225 | Asserts that number is less than.
226 |
227 | ---
228 |
229 | ```js
230 | Assert.lessThanOrEqual(1, 1)
231 | ```
232 |
233 | Asserts that number is less than or equal.
234 |
235 | ---
236 |
237 | ```js
238 | Assert.string("string");
239 | ```
240 |
241 | Assert that value is valid string.
242 |
243 | ---
244 |
245 | ```js
246 | Assert.boolean(true);
247 | ```
248 |
249 | Asserts that value is valid boolean.
250 |
251 | ---
252 |
253 | ```js
254 | Assert.object(1, 1);
255 | ```
256 |
257 | Asserts that value is equal to expected value.
258 |
259 | ---
260 |
261 | ```js
262 | Assert.objectEqual({"key":"value"}, {"key":"value"});
263 | ```
264 |
265 | Asserts that object is equal to expected object.
266 |
267 | ---
268 |
269 | ```js
270 | Assert.object({id: 1});
271 | ```
272 |
273 | Asserts that value is valid object.
274 |
275 | ---
276 |
277 | ```js
278 | Assert.hasFunction("testFunction", {testFunction: () => { alert('test'); }});
279 | ```
280 |
281 | Asserts that object has function.
282 |
283 | ---
284 |
285 | ```js
286 | Assert.hasProperty("test", {test: 'value'});
287 | ```
288 |
289 | Asserts that object has property (it can also be a function).
290 |
291 | ---
292 |
293 | ```js
294 | Assert.isFunction(() => { alert('test'); });
295 | ```
296 |
297 | Asserts that value is valid function.
298 |
299 | ---
300 |
301 | ```js
302 | Assert.array([1, 2, 3, 4, 5]);
303 | ```
304 |
305 | Asserts that value is valid array.
306 |
307 | ---
308 |
309 | ```js
310 | Assert.oneOf(4, [1, 2, 3, 4, 5]);
311 | ```
312 |
313 | Asserts that value is one of expected values.
314 |
315 | ---
316 |
317 |
318 | ```js
319 | Assert.count(0, []);
320 | ```
321 |
322 | Asserts that array have specific number of elements.
323 |
324 | ---
325 |
326 | ```js
327 | Assert.notEmpty(0, [1, 2, 3]);
328 | ```
329 |
330 | Asserts that array is not empty.
331 |
332 | ---
333 |
334 | ```js
335 | Assert.jsonString('{"key": "value"}');
336 | ```
337 |
338 | Asserts that value is valid json string.
339 |
340 | ---
341 |
342 | ```js
343 | Assert.email('norbert@orzechowicz.pl');
344 | ```
345 |
346 | Asserts that string is valid email address.
347 |
348 | ---
349 |
350 | ```js
351 | Assert.url('https://github.com/Tiliqua/assert-js');
352 | ```
353 |
354 | Asserts that string is valid url.
355 |
356 | ---
357 |
358 | ```js
359 | Assert.uuid('3e9009a0-4b2f-414e-bf02-ec0df56fc864');
360 | ```
361 |
362 | Asserts that string is valid UUID.
363 |
364 | ---
365 |
366 | ```js
367 | Assert.hasElement('#div', window.document);
368 | ```
369 |
370 | Asserts that element has other element under selector.
371 |
372 | Example:
373 |
374 | ```js
375 | let dom = new JSDOM(`
`);
376 |
377 | Assert.hasElement('#div', dom.window.document);
378 | ```
379 |
380 | ---
381 |
382 | ```js
383 | Assert.hasAttribute('data-test', window.document.querySelector('#div'));
384 | ```
385 |
386 | Asserts that element has expected attribute (it might be empty).
387 |
388 | Example:
389 |
390 | ```js
391 | let dom = new JSDOM(``);
392 |
393 | Assert.hasAttribute('data-test', dom.window.document.querySelector('#div'));
394 | ```
395 |
396 | ---
397 |
398 | ```js
399 | Assert.hasAttributes(['data-test', 'foo'], window.document.querySelector('#div'));
400 | ```
401 |
402 | Asserts that element has expected attributes (it might be empty).
403 |
404 | Example:
405 |
406 | ```js
407 | let dom = new JSDOM(``);
408 |
409 | Assert.hasAttributes(['data-test','id'], dom.window.document.querySelector('#div'));
410 | ```
411 |
412 | ---
413 |
414 | ```js
415 | Assert.throws(() => { throw new Error('some relevant error message'); }, new Error('some relevant error message'));
416 | ```
417 |
418 | Asserts that function throws expected exception.
419 |
420 | Example:
421 |
422 | ```js
423 | Assert.throws(() => { throw new String('expected message'); }, new String('expected message'));
424 | Assert.throws(() => { throw 'expected message'; }, 'expected message');
425 | Assert.throws(() => { throw new Error(); });
426 | Assert.throws(() => { throw new Error('some not relevant error message'); }, new Error());
427 | Assert.throws(() => { throw new Error('some relevant error message'); }, new Error('some relevant error message'));
428 | ```
429 |
430 | ## Custom exception message
431 |
432 | In order to customize error messages (for easier debugging) you can pass error message as a last parameter into
433 | all assertions.
434 |
435 | Examples:
436 |
437 | ```js
438 | Assert.uuid('test', 'This value is not valid UUID.');
439 | ```
440 |
441 | you can also use variables `expected` and `received` in your messages.
442 |
443 | ```js
444 | Assert.string(1234, 'Expected ${expected} but got ${received}'); // it throws Error("Expected string but got int[1234]")
445 | ```
446 |
--------------------------------------------------------------------------------
/bin/es5/AssertJS/Assert.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
4 |
5 | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
6 |
7 | function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
8 |
9 | function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
10 |
11 | var InvalidValueException = require('./InvalidValueException');
12 |
13 | var ValueConverter = require('./ValueConverter');
14 |
15 | var Assert =
16 | /*#__PURE__*/
17 | function () {
18 | function Assert() {
19 | _classCallCheck(this, Assert);
20 | }
21 |
22 | _createClass(Assert, null, [{
23 | key: "instanceOf",
24 |
25 | /**
26 | * @param {object} objectValue
27 | * @param {function} expectedInstance
28 | * @param {string} [message]
29 | */
30 | value: function instanceOf(objectValue, expectedInstance) {
31 | var message = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "";
32 | this.string(message, "Custom error message passed to Assert.instanceOf needs to be a valid string.");
33 |
34 | if (_typeof(objectValue) !== 'object') {
35 | throw InvalidValueException.expected("object", objectValue, message);
36 | }
37 |
38 | if (!(objectValue instanceof expectedInstance)) {
39 | throw InvalidValueException.expected(expectedInstance.name, objectValue, message.length ? message : "Expected instance of \"${expected}\" but got \"${received}\".");
40 | }
41 | }
42 | }, {
43 | key: "instanceOneOf",
44 | value: function instanceOneOf(objectValue, expectedInstances) {
45 | var message = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "";
46 | this.string(message, "Custom error message passed to Assert.instanceOf needs to be a valid string.");
47 | this.array(expectedInstances);
48 | var instance = expectedInstances.find(function (expectedInstance) {
49 | return objectValue instanceof expectedInstance;
50 | });
51 |
52 | if (instance === undefined) {
53 | throw InvalidValueException.expected(expectedInstances.map(function (instance) {
54 | return ValueConverter.toString(instance);
55 | }).join(', '), objectValue, message.length ? message : "Expected instance of \"${expected}\" but got \"${received}\".");
56 | }
57 | }
58 | /**
59 | * @param {int} integerValue
60 | * @param {string} [message]
61 | */
62 |
63 | }, {
64 | key: "integer",
65 | value: function integer(integerValue) {
66 | var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
67 | this.string(message, "Custom error message passed to Assert.integer needs to be a valid string.");
68 |
69 | if (!Number.isInteger(integerValue)) {
70 | throw InvalidValueException.expected("integer", integerValue, message);
71 | }
72 | }
73 | /**
74 | * @param {number} numberValue
75 | * @param {string} [message]
76 | */
77 |
78 | }, {
79 | key: "number",
80 | value: function number(numberValue) {
81 | var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
82 | this.string(message, "Custom error message passed to Assert.number needs to be a valid string.");
83 |
84 | if (typeof numberValue !== 'number') {
85 | throw InvalidValueException.expected("number", numberValue);
86 | }
87 | }
88 | /**
89 | * @param {string} stringValue
90 | * @param {string} [message]
91 | */
92 |
93 | }, {
94 | key: "string",
95 | value: function string(stringValue) {
96 | var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
97 |
98 | if (typeof message !== "string") {
99 | throw new Error("Custom error message passed to Assert.string needs to be a valid string.");
100 | }
101 |
102 | if (typeof stringValue !== "string") {
103 | throw InvalidValueException.expected("string", stringValue, message);
104 | }
105 | }
106 | /**
107 | * @param {boolean} booleanValue
108 | * @param {string} [message]
109 | */
110 |
111 | }, {
112 | key: "boolean",
113 | value: function boolean(booleanValue) {
114 | var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
115 | this.string(message, "Custom error message passed to Assert.boolean needs to be a valid string.");
116 |
117 | if (typeof booleanValue !== 'boolean') {
118 | throw InvalidValueException.expected("boolean", booleanValue, message);
119 | }
120 | }
121 | /**
122 | * @param {boolean} value
123 | * @param {string} [message]
124 | */
125 |
126 | }, {
127 | key: "true",
128 | value: function _true(value) {
129 | var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
130 | this["boolean"](value);
131 | this.string(message, "Custom error message passed to Assert.true needs to be a valid string.");
132 |
133 | if (value !== true) {
134 | throw InvalidValueException.expected("true", value, message);
135 | }
136 | }
137 | /**
138 | * @param {boolean} value
139 | * @param {string} [message]
140 | */
141 |
142 | }, {
143 | key: "false",
144 | value: function _false(value) {
145 | var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
146 | this["boolean"](value);
147 | this.string(message, "Custom error message passed to Assert.false needs to be a valid string.");
148 |
149 | if (value !== false) {
150 | throw InvalidValueException.expected("false", value, message);
151 | }
152 | }
153 | /**
154 | * @param value
155 | * @param expectedValue
156 | * @param {string} [message]
157 | */
158 |
159 | }, {
160 | key: "equal",
161 | value: function equal(value, expectedValue) {
162 | var message = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "";
163 |
164 | if (_typeof(value) !== 'object') {
165 | this["true"](value === expectedValue, message ? message : "Expected value ".concat(ValueConverter.toString(value), " to be equals ").concat(ValueConverter.toString(expectedValue), " but it's not."));
166 | } else {
167 | this.objectEqual(value, expectedValue, message ? message : "Expected value ".concat(ValueConverter.toString(value), " to be equals ").concat(ValueConverter.toString(expectedValue), " but it's not."));
168 | }
169 | }
170 | /**
171 | * @param {object} object
172 | * @param {object} expectedObject
173 | * @param {string} [message]
174 | */
175 |
176 | }, {
177 | key: "objectEqual",
178 | value: function objectEqual(object, expectedObject) {
179 | var _this = this;
180 |
181 | var message = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "";
182 | this.object(object, message);
183 | this.object(expectedObject, message);
184 | var objectProperties = Object.getOwnPropertyNames(object);
185 | var expectedObjectProperties = Object.getOwnPropertyNames(expectedObject);
186 | this["true"](objectProperties.length === expectedObjectProperties.length, message ? message : "Expected object ".concat(ValueConverter.toString(object), " to be equals ").concat(ValueConverter.toString(expectedObject), " but it's not."));
187 | objectProperties.forEach(function (objectProperty) {
188 | _this.equal(object[objectProperty], expectedObject[objectProperty], message ? message : "Expected object ".concat(ValueConverter.toString(object), " to be equals ").concat(ValueConverter.toString(expectedObject), " but it's not."));
189 | });
190 | }
191 | /**
192 | * @param {object} objectValue
193 | * @param {string} [message]
194 | */
195 |
196 | }, {
197 | key: "object",
198 | value: function object(objectValue) {
199 | var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
200 | this.string(message, "Custom error message passed to Assert.object needs to be a valid string.");
201 |
202 | if (_typeof(objectValue) !== 'object') {
203 | throw InvalidValueException.expected("object", objectValue, message);
204 | }
205 | }
206 | /**
207 | * @param {string} expectedFunctionName
208 | * @param {object} objectValue
209 | * @param {string} [message]
210 | */
211 |
212 | }, {
213 | key: "hasFunction",
214 | value: function hasFunction(expectedFunctionName, objectValue) {
215 | var message = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "";
216 | this.string(expectedFunctionName);
217 | this.object(objectValue);
218 | this.string(message, "Custom error message passed to Assert.hasFunction needs to be a valid string.");
219 |
220 | if (typeof objectValue[expectedFunctionName] !== 'function') {
221 | throw InvalidValueException.expected("object to has function \"".concat(expectedFunctionName, "\""), objectValue, message);
222 | }
223 | }
224 | /**
225 | * @param {string} expectedPropertyName
226 | * @param {object} objectValue
227 | * @param {string} [message]
228 | */
229 |
230 | }, {
231 | key: "hasProperty",
232 | value: function hasProperty(expectedPropertyName, objectValue) {
233 | var message = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "";
234 | this.string(expectedPropertyName);
235 | this.object(objectValue);
236 | this.string(message, "Custom error message passed to Assert.hasProperty needs to be a valid string.");
237 |
238 | if (typeof objectValue[expectedPropertyName] === 'undefined') {
239 | throw InvalidValueException.expected("object to has property \"".concat(expectedPropertyName, "\""), objectValue, message);
240 | }
241 | }
242 | /**
243 | * @param {array} expectedProperties
244 | * @param {object} objectValue
245 | * @param {string} [message]
246 | */
247 |
248 | }, {
249 | key: "hasProperties",
250 | value: function hasProperties(expectedProperties, objectValue) {
251 | var message = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "";
252 | this.object(objectValue);
253 | this.containsOnlyString(expectedProperties);
254 | this.string(message, "Custom error message passed to Assert.hasProperties needs to be a valid string.");
255 | expectedProperties.map(function (expectedProperty) {
256 | if (typeof objectValue[expectedProperty] === 'undefined') {
257 | throw InvalidValueException.expected("object to has properties \"".concat(expectedProperties.join(', '), "\""), objectValue, message);
258 | }
259 | });
260 | }
261 | /**
262 | * @param {array} arrayValue
263 | * @param {string} [message]
264 | */
265 |
266 | }, {
267 | key: "array",
268 | value: function array(arrayValue) {
269 | var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
270 | this.string(message, "Custom error message passed to Assert.array needs to be a valid string.");
271 |
272 | if (!Array.isArray(arrayValue)) {
273 | throw InvalidValueException.expected("array", arrayValue, message);
274 | }
275 | }
276 | /**
277 | * @param {*} value
278 | * @param {array} expectedElements
279 | * @param {string} [message]
280 | */
281 |
282 | }, {
283 | key: "oneOf",
284 | value: function oneOf(value, expectedElements) {
285 | var message = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "";
286 | this.string(message, "Custom error message passed to Assert.array needs to be a valid string.");
287 | this.array(expectedElements);
288 | var foundValue = expectedElements.find(function (expectedInstance) {
289 | return value === expectedInstance;
290 | });
291 |
292 | if (foundValue === undefined) {
293 | throw InvalidValueException.expected(expectedElements.map(function (elemenet) {
294 | return ValueConverter.toString(elemenet);
295 | }).join(', '), value, message.length ? message : "Expected one of \"${expected}\" but got \"${received}\".");
296 | }
297 | }
298 | /**
299 | * @param {function} functionValue
300 | * @param {string} [message]
301 | */
302 |
303 | }, {
304 | key: "isFunction",
305 | value: function isFunction(functionValue) {
306 | var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
307 | this.string(message, "Custom error message passed to Assert.isFunction needs to be a valid string.");
308 |
309 | if (typeof functionValue !== 'function') {
310 | throw InvalidValueException.expected("function", functionValue, message);
311 | }
312 | }
313 | /**
314 | * @param {int} expected
315 | * @param {int} integerValue
316 | * @param {string} [message]
317 | */
318 |
319 | }, {
320 | key: "greaterThan",
321 | value: function greaterThan(expected, integerValue) {
322 | var message = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "";
323 | this.number(expected);
324 | this.number(integerValue);
325 | this.string(message, "Custom error message passed to Assert.greaterThan needs to be a valid string.");
326 |
327 | if (integerValue <= expected) {
328 | throw new Error(message.length > 0 ? message : "Expected value ".concat(integerValue, " to be greater than ").concat(expected));
329 | }
330 | }
331 | /**
332 | * @param {int} expected
333 | * @param {int} integerValue
334 | * @param {string} [message]
335 | */
336 |
337 | }, {
338 | key: "greaterThanOrEqual",
339 | value: function greaterThanOrEqual(expected, integerValue) {
340 | var message = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "";
341 | this.number(expected);
342 | this.number(integerValue);
343 | this.string(message, "Custom error message passed to Assert.greaterThanOrEqual needs to be a valid string.");
344 |
345 | if (integerValue < expected) {
346 | throw new Error(message.length > 0 ? message : "Expected value ".concat(integerValue, " to be greater than ").concat(expected, " or equal"));
347 | }
348 | }
349 | /**
350 | * @param {int} expected
351 | * @param {int} integerValue
352 | * @param {string} [message]
353 | */
354 |
355 | }, {
356 | key: "lessThan",
357 | value: function lessThan(expected, integerValue) {
358 | var message = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "";
359 | this.number(expected);
360 | this.number(integerValue);
361 | this.string(message, "Custom error message passed to Assert.lessThan needs to be a valid string.");
362 |
363 | if (integerValue >= expected) {
364 | throw new Error(message.length > 0 ? message : "Expected value ".concat(integerValue, " to be less than ").concat(expected));
365 | }
366 | }
367 | /**
368 | * @param {int} expected
369 | * @param {int} integerValue
370 | * @param {string} [message]
371 | */
372 |
373 | }, {
374 | key: "lessThanOrEqual",
375 | value: function lessThanOrEqual(expected, integerValue) {
376 | var message = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "";
377 | this.number(expected);
378 | this.number(integerValue);
379 | this.string(message, "Custom error message passed to Assert.lessThanOrEqual needs to be a valid string.");
380 |
381 | if (integerValue > expected) {
382 | throw new Error(message.length > 0 ? message : "Expected value ".concat(integerValue, " to be less than ").concat(expected, " or equal"));
383 | }
384 | }
385 | /**
386 | * @param {array} arrayValue
387 | * @param {function} expectedInstance
388 | * @param {string} [message]
389 | */
390 |
391 | }, {
392 | key: "containsOnly",
393 | value: function containsOnly(arrayValue, expectedInstance) {
394 | var message = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "";
395 | this.array(arrayValue, "Assert.containsOnly require valid array, got \"${received}\".");
396 | this.string(message, "Custom error message passed to Assert.containsOnly needs to be a valid string.");
397 | var _iteratorNormalCompletion = true;
398 | var _didIteratorError = false;
399 | var _iteratorError = undefined;
400 |
401 | try {
402 | for (var _iterator = arrayValue[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
403 | var element = _step.value;
404 |
405 | try {
406 | this.instanceOf(element, expectedInstance, message);
407 | } catch (error) {
408 | throw InvalidValueException.expected(expectedInstance.name, element, message.length ? message : "Expected instance of \"${expected}\" but got \"${received}\".");
409 | }
410 | }
411 | } catch (err) {
412 | _didIteratorError = true;
413 | _iteratorError = err;
414 | } finally {
415 | try {
416 | if (!_iteratorNormalCompletion && _iterator["return"] != null) {
417 | _iterator["return"]();
418 | }
419 | } finally {
420 | if (_didIteratorError) {
421 | throw _iteratorError;
422 | }
423 | }
424 | }
425 | }
426 | /**
427 | * @param {array} arrayValue
428 | * @param {string} [message]
429 | */
430 |
431 | }, {
432 | key: "containsOnlyString",
433 | value: function containsOnlyString(arrayValue) {
434 | var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
435 | this.array(arrayValue, "Assert.containsOnlyString require valid array, got \"${received}\".");
436 | this.string(message, "Custom error message passed to Assert.containsOnly needs to be a valid string.");
437 | var _iteratorNormalCompletion2 = true;
438 | var _didIteratorError2 = false;
439 | var _iteratorError2 = undefined;
440 |
441 | try {
442 | for (var _iterator2 = arrayValue[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
443 | var element = _step2.value;
444 |
445 | try {
446 | this.string(element, message);
447 | } catch (error) {
448 | throw InvalidValueException.expected('string', arrayValue.map(function (value) {
449 | return ValueConverter.toString(value);
450 | }).join(', '), message.length ? message : "Expected array of \"${expected}\" but got \"${received}\".");
451 | }
452 | }
453 | } catch (err) {
454 | _didIteratorError2 = true;
455 | _iteratorError2 = err;
456 | } finally {
457 | try {
458 | if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) {
459 | _iterator2["return"]();
460 | }
461 | } finally {
462 | if (_didIteratorError2) {
463 | throw _iteratorError2;
464 | }
465 | }
466 | }
467 | }
468 | /**
469 | * @param {array} arrayValue
470 | * @param {string} [message]
471 | */
472 |
473 | }, {
474 | key: "containsOnlyInteger",
475 | value: function containsOnlyInteger(arrayValue) {
476 | var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
477 | this.array(arrayValue, "Assert.containsOnlyInteger require valid array, got \"${received}\".");
478 | this.string(message, "Custom error message passed to Assert.containsOnly needs to be a valid string.");
479 | var _iteratorNormalCompletion3 = true;
480 | var _didIteratorError3 = false;
481 | var _iteratorError3 = undefined;
482 |
483 | try {
484 | for (var _iterator3 = arrayValue[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
485 | var element = _step3.value;
486 |
487 | try {
488 | this.integer(element, message);
489 | } catch (error) {
490 | throw InvalidValueException.expected('integer', arrayValue.map(function (value) {
491 | return ValueConverter.toString(value);
492 | }).join(', '), message.length ? message : "Expected array of \"${expected}\" but got \"${received}\".");
493 | }
494 | }
495 | } catch (err) {
496 | _didIteratorError3 = true;
497 | _iteratorError3 = err;
498 | } finally {
499 | try {
500 | if (!_iteratorNormalCompletion3 && _iterator3["return"] != null) {
501 | _iterator3["return"]();
502 | }
503 | } finally {
504 | if (_didIteratorError3) {
505 | throw _iteratorError3;
506 | }
507 | }
508 | }
509 | }
510 | /**
511 | * @param {array} arrayValue
512 | * @param {string} [message]
513 | */
514 |
515 | }, {
516 | key: "containsOnlyNumber",
517 | value: function containsOnlyNumber(arrayValue) {
518 | var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
519 | this.array(arrayValue, "Assert.containsOnlyNumber require valid array, got \"${received}\".");
520 | this.string(message, "Custom error message passed to Assert.containsOnly needs to be a valid string.");
521 | var _iteratorNormalCompletion4 = true;
522 | var _didIteratorError4 = false;
523 | var _iteratorError4 = undefined;
524 |
525 | try {
526 | for (var _iterator4 = arrayValue[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
527 | var element = _step4.value;
528 |
529 | try {
530 | this.number(element, message);
531 | } catch (error) {
532 | throw InvalidValueException.expected('number', arrayValue.map(function (value) {
533 | return ValueConverter.toString(value);
534 | }).join(', '), message.length ? message : "Expected array of \"${expected}\" but got \"${received}\".");
535 | }
536 | }
537 | } catch (err) {
538 | _didIteratorError4 = true;
539 | _iteratorError4 = err;
540 | } finally {
541 | try {
542 | if (!_iteratorNormalCompletion4 && _iterator4["return"] != null) {
543 | _iterator4["return"]();
544 | }
545 | } finally {
546 | if (_didIteratorError4) {
547 | throw _iteratorError4;
548 | }
549 | }
550 | }
551 | }
552 | /**
553 | * @param {int} expectedCount
554 | * @param {array} arrayValue
555 | * @param {string} [message]
556 | */
557 |
558 | }, {
559 | key: "count",
560 | value: function count(expectedCount, arrayValue) {
561 | var message = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "";
562 | this.integer(expectedCount);
563 | this.array(arrayValue);
564 | this.string(message, "Custom error message passed to Assert.count needs to be a valid string.");
565 |
566 | if (arrayValue.length !== expectedCount) {
567 | throw new Error(message.length ? message : "Expected count ".concat(expectedCount, ", got ").concat(arrayValue.length));
568 | }
569 | }
570 | /**
571 | * @param {*} value
572 | * @param {string} [message]
573 | */
574 |
575 | }, {
576 | key: "notEmpty",
577 | value: function notEmpty(value) {
578 | var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
579 | this.string(message, "Custom error message passed to Assert.empty needs to be a valid string.");
580 |
581 | if (value.length === 0) {
582 | throw InvalidValueException.expected("not empty value", value, message);
583 | }
584 | }
585 | /**
586 | * @param {int} integerValue
587 | * @param {string} [message]
588 | */
589 |
590 | }, {
591 | key: "oddNumber",
592 | value: function oddNumber(integerValue) {
593 | var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
594 | this.integer(integerValue);
595 | this.string(message, "Custom error message passed to Assert.oddNumber needs to be a valid string.");
596 |
597 | if (integerValue % 2 !== 1) {
598 | throw InvalidValueException.expected("odd number", integerValue, message);
599 | }
600 | }
601 | /**
602 | * @param {int} integerValue
603 | * @param {string} [message]
604 | */
605 |
606 | }, {
607 | key: "evenNumber",
608 | value: function evenNumber(integerValue) {
609 | var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
610 | this.integer(integerValue);
611 | this.string(message, "Custom error message passed to Assert.evenNumber needs to be a valid string.");
612 |
613 | if (integerValue % 2 !== 0) {
614 | throw InvalidValueException.expected("even number", integerValue, message);
615 | }
616 | }
617 | /**
618 | * @param {string} stringValue
619 | * @param {string} [message]
620 | */
621 |
622 | }, {
623 | key: "jsonString",
624 | value: function jsonString(stringValue) {
625 | var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
626 | this.string(stringValue);
627 | this.string(message, "Custom error message passed to Assert.jsonString needs to be a valid string.");
628 |
629 | try {
630 | JSON.parse(stringValue);
631 | } catch (e) {
632 | throw InvalidValueException.expected("json string", stringValue, message);
633 | }
634 | }
635 | /**
636 | * @param {string} emailValue
637 | * @param {string} [message]
638 | */
639 |
640 | }, {
641 | key: "email",
642 | value: function email(emailValue) {
643 | var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
644 | this.string(emailValue);
645 | this.string(message, "Custom error message passed to Assert.email needs to be a valid string.");
646 | var regexp = /^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i;
647 |
648 | if (!regexp.test(emailValue)) {
649 | throw InvalidValueException.expected("valid email address", emailValue, message);
650 | }
651 | }
652 | /**
653 | * @param {string} urlValue
654 | * @param {string} [message]
655 | */
656 |
657 | }, {
658 | key: "url",
659 | value: function url(urlValue) {
660 | var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
661 | this.string(urlValue);
662 | this.string(message, "Custom error message passed to Assert.url needs to be a valid string.");
663 | var regexp = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/;
664 |
665 | if (!regexp.test(urlValue)) {
666 | throw InvalidValueException.expected("valid url", urlValue, message);
667 | }
668 | }
669 | /**
670 | * @param {string} uuidValue
671 | * @param {string} [message]
672 | */
673 |
674 | }, {
675 | key: "uuid",
676 | value: function uuid(uuidValue) {
677 | var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
678 | this.string(uuidValue);
679 | this.string(message, "Custom error message passed to Assert.uuid needs to be a valid string.");
680 | var regexp = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
681 |
682 | if (!regexp.test(uuidValue)) {
683 | throw InvalidValueException.expected("valid uuid", uuidValue, message);
684 | }
685 | }
686 | /**
687 | * @param {string} selector
688 | * @param {HTMLElement|HTMLDocument} htmlElement
689 | * @param {string} [message]
690 | */
691 |
692 | }, {
693 | key: "hasElement",
694 | value: function hasElement(selector, htmlElement) {
695 | var message = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "";
696 | this.string(selector);
697 | this.instanceOneOf(htmlElement, [HTMLElement, HTMLDocument]);
698 | this.string(message, "Custom error message passed to Assert.hasProperty needs to be a valid string.");
699 |
700 | if (null === htmlElement.querySelector(selector)) {
701 | throw InvalidValueException.expected("html element to has element under selector \"".concat(selector, "\""), htmlElement.outerHTML, message);
702 | }
703 | }
704 | /**
705 | * @param {string} attributeName
706 | * @param {HTMLElement} htmlElement
707 | * @param {string} [message]
708 | */
709 |
710 | }, {
711 | key: "hasAttribute",
712 | value: function hasAttribute(attributeName, htmlElement) {
713 | var message = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "";
714 | this.string(attributeName);
715 | this.instanceOf(htmlElement, HTMLElement);
716 | this.string(message, "Custom error message passed to Assert.hasAttribute needs to be a valid string.");
717 | var attribute = htmlElement.getAttribute(attributeName);
718 |
719 | if (null === attribute) {
720 | throw InvalidValueException.expected("html element with attribute \"".concat(attributeName, "\""), htmlElement.outerHTML, message);
721 | }
722 | }
723 | /**
724 | * @param {array} attributes
725 | * @param {HTMLElement} htmlElement
726 | * @param {string} [message]
727 | */
728 |
729 | }, {
730 | key: "hasAttributes",
731 | value: function hasAttributes(attributes, htmlElement) {
732 | var _this2 = this;
733 |
734 | var message = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "";
735 | this.containsOnlyString(attributes);
736 | this.instanceOf(htmlElement, HTMLElement);
737 | this.string(message, "Custom error message passed to Assert.hasAttributes needs to be a valid string.");
738 | attributes.map(function (attribute) {
739 | try {
740 | _this2.hasAttribute(attribute, htmlElement);
741 | } catch (e) {
742 | throw InvalidValueException.expected("html element with attributes \"".concat(attributes.join(', '), "\""), htmlElement.outerHTML, message);
743 | }
744 | });
745 | }
746 | /**
747 | * @param {function} callback
748 | * @param {object} [expectedError]
749 | */
750 |
751 | }, {
752 | key: "throws",
753 | value: function throws(callback) {
754 | var expectedError = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Error();
755 | this.isFunction(callback);
756 |
757 | try {
758 | callback();
759 | } catch (error) {
760 | if (_typeof(error) === 'object' && error instanceof Error && _typeof(expectedError) === 'object' && expectedError instanceof Error) {
761 | if (expectedError.message.length) {
762 | this.equal(error.message, expectedError.message, "Expected exception message \"".concat(error.message, "\" to be equals \"").concat(expectedError.message, "\" but it's not."));
763 | }
764 |
765 | return;
766 | }
767 |
768 | this.equal(error, expectedError, "Expected error of type ".concat(ValueConverter.toString(error), " to be equals ").concat(ValueConverter.toString(expectedError), " but it's not."));
769 | return;
770 | }
771 |
772 | throw InvalidValueException.expected(ValueConverter.toString(expectedError), null, "Expected from callback to throw an Error \"${expected}\" but it didn't.");
773 | }
774 | }]);
775 |
776 | return Assert;
777 | }();
778 |
779 | module.exports = Assert;
--------------------------------------------------------------------------------
/bin/es5/AssertJS/InvalidValueException.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
4 |
5 | function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
6 |
7 | function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
8 |
9 | var MessageFactory = require('./MessageFactory');
10 |
11 | var ValueConverter = require('./ValueConverter');
12 |
13 | var InvalidValueException =
14 | /*#__PURE__*/
15 | function () {
16 | function InvalidValueException() {
17 | _classCallCheck(this, InvalidValueException);
18 | }
19 |
20 | _createClass(InvalidValueException, null, [{
21 | key: "expected",
22 |
23 | /**
24 | * @param {string} type
25 | * @param {*} value
26 | * @param {string} [message]
27 | * @returns {Error}
28 | */
29 | value: function expected(type, value) {
30 | var message = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "";
31 |
32 | if (typeof message !== 'string') {
33 | throw new Error("Expected string but got \"".concat(ValueConverter.toString(message), "\"."));
34 | }
35 |
36 | if (message.length) {
37 | return new Error(MessageFactory.create(message, {
38 | expected: type,
39 | received: ValueConverter.toString(value)
40 | }));
41 | }
42 |
43 | return new Error("Expected ".concat(type, " but got \"").concat(ValueConverter.toString(value), "\"."));
44 | }
45 | }]);
46 |
47 | return InvalidValueException;
48 | }();
49 |
50 | module.exports = InvalidValueException;
--------------------------------------------------------------------------------
/bin/es5/AssertJS/MessageFactory.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
4 |
5 | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
6 |
7 | function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
8 |
9 | function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
10 |
11 | var VALUE_NAME_REGEXP = /\${(.*?)}/g;
12 |
13 | var MessageFactory =
14 | /*#__PURE__*/
15 | function () {
16 | function MessageFactory() {
17 | _classCallCheck(this, MessageFactory);
18 | }
19 |
20 | _createClass(MessageFactory, null, [{
21 | key: "create",
22 |
23 | /**
24 | * @param {string} template
25 | * @param {object} [data]
26 | */
27 | value: function create(template) {
28 | var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
29 |
30 | if (typeof template !== 'string') {
31 | throw new Error("Expected string but got \"".concat(ValueConverter.toString(template), "\"."));
32 | }
33 |
34 | if (_typeof(data) !== 'object') {
35 | throw new Error("Expected string but got \"".concat(ValueConverter.toString(data), "\"."));
36 | }
37 |
38 | return template.replace(VALUE_NAME_REGEXP, function (placeholder, propertyName) {
39 | if (data.hasOwnProperty(propertyName)) {
40 | return data[propertyName];
41 | }
42 |
43 | return placeholder;
44 | });
45 | }
46 | }]);
47 |
48 | return MessageFactory;
49 | }();
50 |
51 | module.exports = MessageFactory;
--------------------------------------------------------------------------------
/bin/es5/AssertJS/ValueConverter.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
4 |
5 | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
6 |
7 | function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
8 |
9 | function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
10 |
11 | var ValueConverter =
12 | /*#__PURE__*/
13 | function () {
14 | function ValueConverter() {
15 | _classCallCheck(this, ValueConverter);
16 | }
17 |
18 | _createClass(ValueConverter, null, [{
19 | key: "toString",
20 |
21 | /**
22 | * @param {*} value
23 | * @returns {string}
24 | */
25 | value: function toString(value) {
26 | if (typeof value === 'string') {
27 | return "string[\"".concat(value, "\"]");
28 | }
29 |
30 | if (typeof value === 'number') {
31 | if (Number.isInteger(value)) {
32 | return "int[".concat(value, "]");
33 | }
34 |
35 | return "float[".concat(value, "]");
36 | }
37 |
38 | if (typeof value === 'boolean') {
39 | return "boolean[".concat(value ? "true" : "false", "]");
40 | }
41 |
42 | if (typeof value === 'function') {
43 | return "function[".concat(value.toString(), "]");
44 | }
45 |
46 | if (_typeof(value) === 'object') {
47 | if (Array.isArray(value)) {
48 | return "array[length: ".concat(value.length, "]");
49 | }
50 |
51 | if (value instanceof Map) {
52 | return "Map[size: ".concat(value.size, "]");
53 | }
54 |
55 | if (value instanceof WeakMap) {
56 | return "WeakMap[]";
57 | }
58 |
59 | if (value instanceof Set) {
60 | return "Set[size: ".concat(value.size, "]");
61 | }
62 |
63 | if (value instanceof WeakSet) {
64 | return "WeakSet[]";
65 | }
66 |
67 | if (value instanceof String) {
68 | return "String[\"".concat(value, "\"]");
69 | }
70 |
71 | if (value instanceof Number) {
72 | var source = value.valueOf();
73 |
74 | if (Number.isInteger(source)) {
75 | return "Number:int[".concat(source, "]");
76 | }
77 |
78 | return "Number:float[".concat(source, "]");
79 | }
80 |
81 | if (value instanceof Boolean) {
82 | return "Boolean[".concat(value.valueOf() ? "true" : "false", "]");
83 | }
84 |
85 | if (value instanceof Date) {
86 | return "Date[\"".concat(value.toUTCString(), "\"]");
87 | }
88 |
89 | if (value instanceof RegExp) {
90 | return "RegExp[".concat(value.toString(), "]");
91 | }
92 |
93 | return "object[".concat(JSON.stringify(value), "]");
94 | }
95 |
96 | if (typeof value === 'undefined') {
97 | return 'undefined';
98 | }
99 |
100 | throw "Unhandled type ".concat(_typeof(value));
101 | }
102 | }]);
103 |
104 | return ValueConverter;
105 | }();
106 |
107 | module.exports = ValueConverter;
--------------------------------------------------------------------------------
/bin/es5/assert-js.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var assert = require('./AssertJS/Assert');
4 |
5 | module.exports = assert;
6 |
7 | if (typeof window !== 'undefined') {
8 | window.Assert = assert;
9 | }
--------------------------------------------------------------------------------
/bin/es5/assert-js.min.js:
--------------------------------------------------------------------------------
1 | !function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)r.d(n,o,function(t){return e[t]}.bind(null,o));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=1)}([function(e,t,r){"use strict";function n(e){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function o(e,t){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:"";if(this.string(r,"Custom error message passed to Assert.instanceOf needs to be a valid string."),"object"!==n(e))throw i.expected("object",e,r);if(!(e instanceof t))throw i.expected(t.name,e,r.length?r:'Expected instance of "${expected}" but got "${received}".')}},{key:"instanceOneOf",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";this.string(r,"Custom error message passed to Assert.instanceOf needs to be a valid string."),this.array(t);var n=t.find((function(t){return e instanceof t}));if(void 0===n)throw i.expected(t.map((function(e){return s.toString(e)})).join(", "),e,r.length?r:'Expected instance of "${expected}" but got "${received}".')}},{key:"integer",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(this.string(t,"Custom error message passed to Assert.integer needs to be a valid string."),!Number.isInteger(e))throw i.expected("integer",e,t)}},{key:"number",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(this.string(t,"Custom error message passed to Assert.number needs to be a valid string."),"number"!=typeof e)throw i.expected("number",e)}},{key:"string",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if("string"!=typeof t)throw new Error("Custom error message passed to Assert.string needs to be a valid string.");if("string"!=typeof e)throw i.expected("string",e,t)}},{key:"boolean",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(this.string(t,"Custom error message passed to Assert.boolean needs to be a valid string."),"boolean"!=typeof e)throw i.expected("boolean",e,t)}},{key:"true",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(this.boolean(e),this.string(t,"Custom error message passed to Assert.true needs to be a valid string."),!0!==e)throw i.expected("true",e,t)}},{key:"false",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(this.boolean(e),this.string(t,"Custom error message passed to Assert.false needs to be a valid string."),!1!==e)throw i.expected("false",e,t)}},{key:"equal",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";"object"!==n(e)?this.true(e===t,r||"Expected value ".concat(s.toString(e)," to be equals ").concat(s.toString(t)," but it's not.")):this.objectEqual(e,t,r||"Expected value ".concat(s.toString(e)," to be equals ").concat(s.toString(t)," but it's not."))}},{key:"objectEqual",value:function(e,t){var r=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";this.object(e,n),this.object(t,n);var o=Object.getOwnPropertyNames(e),i=Object.getOwnPropertyNames(t);this.true(o.length===i.length,n||"Expected object ".concat(s.toString(e)," to be equals ").concat(s.toString(t)," but it's not.")),o.forEach((function(o){r.equal(e[o],t[o],n||"Expected object ".concat(s.toString(e)," to be equals ").concat(s.toString(t)," but it's not."))}))}},{key:"object",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(this.string(t,"Custom error message passed to Assert.object needs to be a valid string."),"object"!==n(e))throw i.expected("object",e,t)}},{key:"hasFunction",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";if(this.string(e),this.object(t),this.string(r,"Custom error message passed to Assert.hasFunction needs to be a valid string."),"function"!=typeof t[e])throw i.expected('object to has function "'.concat(e,'"'),t,r)}},{key:"hasProperty",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";if(this.string(e),this.object(t),this.string(r,"Custom error message passed to Assert.hasProperty needs to be a valid string."),void 0===t[e])throw i.expected('object to has property "'.concat(e,'"'),t,r)}},{key:"hasProperties",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";this.object(t),this.containsOnlyString(e),this.string(r,"Custom error message passed to Assert.hasProperties needs to be a valid string."),e.map((function(n){if(void 0===t[n])throw i.expected('object to has properties "'.concat(e.join(", "),'"'),t,r)}))}},{key:"array",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(this.string(t,"Custom error message passed to Assert.array needs to be a valid string."),!Array.isArray(e))throw i.expected("array",e,t)}},{key:"oneOf",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";this.string(r,"Custom error message passed to Assert.array needs to be a valid string."),this.array(t);var n=t.find((function(t){return e===t}));if(void 0===n)throw i.expected(t.map((function(e){return s.toString(e)})).join(", "),e,r.length?r:'Expected one of "${expected}" but got "${received}".')}},{key:"isFunction",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(this.string(t,"Custom error message passed to Assert.isFunction needs to be a valid string."),"function"!=typeof e)throw i.expected("function",e,t)}},{key:"greaterThan",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";if(this.number(e),this.number(t),this.string(r,"Custom error message passed to Assert.greaterThan needs to be a valid string."),t<=e)throw new Error(r.length>0?r:"Expected value ".concat(t," to be greater than ").concat(e))}},{key:"greaterThanOrEqual",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";if(this.number(e),this.number(t),this.string(r,"Custom error message passed to Assert.greaterThanOrEqual needs to be a valid string."),t0?r:"Expected value ".concat(t," to be greater than ").concat(e," or equal"))}},{key:"lessThan",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";if(this.number(e),this.number(t),this.string(r,"Custom error message passed to Assert.lessThan needs to be a valid string."),t>=e)throw new Error(r.length>0?r:"Expected value ".concat(t," to be less than ").concat(e))}},{key:"lessThanOrEqual",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";if(this.number(e),this.number(t),this.string(r,"Custom error message passed to Assert.lessThanOrEqual needs to be a valid string."),t>e)throw new Error(r.length>0?r:"Expected value ".concat(t," to be less than ").concat(e," or equal"))}},{key:"containsOnly",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";this.array(e,'Assert.containsOnly require valid array, got "${received}".'),this.string(r,"Custom error message passed to Assert.containsOnly needs to be a valid string.");var n=!0,o=!1,s=void 0;try{for(var a,c=e[Symbol.iterator]();!(n=(a=c.next()).done);n=!0){var u=a.value;try{this.instanceOf(u,t,r)}catch(e){throw i.expected(t.name,u,r.length?r:'Expected instance of "${expected}" but got "${received}".')}}}catch(e){o=!0,s=e}finally{try{n||null==c.return||c.return()}finally{if(o)throw s}}}},{key:"containsOnlyString",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";this.array(e,'Assert.containsOnlyString require valid array, got "${received}".'),this.string(t,"Custom error message passed to Assert.containsOnly needs to be a valid string.");var r=!0,n=!1,o=void 0;try{for(var a,c=e[Symbol.iterator]();!(r=(a=c.next()).done);r=!0){var u=a.value;try{this.string(u,t)}catch(r){throw i.expected("string",e.map((function(e){return s.toString(e)})).join(", "),t.length?t:'Expected array of "${expected}" but got "${received}".')}}}catch(e){n=!0,o=e}finally{try{r||null==c.return||c.return()}finally{if(n)throw o}}}},{key:"containsOnlyInteger",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";this.array(e,'Assert.containsOnlyInteger require valid array, got "${received}".'),this.string(t,"Custom error message passed to Assert.containsOnly needs to be a valid string.");var r=!0,n=!1,o=void 0;try{for(var a,c=e[Symbol.iterator]();!(r=(a=c.next()).done);r=!0){var u=a.value;try{this.integer(u,t)}catch(r){throw i.expected("integer",e.map((function(e){return s.toString(e)})).join(", "),t.length?t:'Expected array of "${expected}" but got "${received}".')}}}catch(e){n=!0,o=e}finally{try{r||null==c.return||c.return()}finally{if(n)throw o}}}},{key:"containsOnlyNumber",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";this.array(e,'Assert.containsOnlyNumber require valid array, got "${received}".'),this.string(t,"Custom error message passed to Assert.containsOnly needs to be a valid string.");var r=!0,n=!1,o=void 0;try{for(var a,c=e[Symbol.iterator]();!(r=(a=c.next()).done);r=!0){var u=a.value;try{this.number(u,t)}catch(r){throw i.expected("number",e.map((function(e){return s.toString(e)})).join(", "),t.length?t:'Expected array of "${expected}" but got "${received}".')}}}catch(e){n=!0,o=e}finally{try{r||null==c.return||c.return()}finally{if(n)throw o}}}},{key:"count",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";if(this.integer(e),this.array(t),this.string(r,"Custom error message passed to Assert.count needs to be a valid string."),t.length!==e)throw new Error(r.length?r:"Expected count ".concat(e,", got ").concat(t.length))}},{key:"notEmpty",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(this.string(t,"Custom error message passed to Assert.empty needs to be a valid string."),0===e.length)throw i.expected("not empty value",e,t)}},{key:"oddNumber",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(this.integer(e),this.string(t,"Custom error message passed to Assert.oddNumber needs to be a valid string."),e%2!=1)throw i.expected("odd number",e,t)}},{key:"evenNumber",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(this.integer(e),this.string(t,"Custom error message passed to Assert.evenNumber needs to be a valid string."),e%2!=0)throw i.expected("even number",e,t)}},{key:"jsonString",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";this.string(e),this.string(t,"Custom error message passed to Assert.jsonString needs to be a valid string.");try{JSON.parse(e)}catch(r){throw i.expected("json string",e,t)}}},{key:"email",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";this.string(e),this.string(t,"Custom error message passed to Assert.email needs to be a valid string.");var r=/^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i;if(!r.test(e))throw i.expected("valid email address",e,t)}},{key:"url",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";this.string(e),this.string(t,"Custom error message passed to Assert.url needs to be a valid string.");var r=/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/;if(!r.test(e))throw i.expected("valid url",e,t)}},{key:"uuid",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";this.string(e),this.string(t,"Custom error message passed to Assert.uuid needs to be a valid string.");var r=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;if(!r.test(e))throw i.expected("valid uuid",e,t)}},{key:"hasElement",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";if(this.string(e),this.instanceOneOf(t,[HTMLElement,HTMLDocument]),this.string(r,"Custom error message passed to Assert.hasProperty needs to be a valid string."),null===t.querySelector(e))throw i.expected('html element to has element under selector "'.concat(e,'"'),t.outerHTML,r)}},{key:"hasAttribute",value:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";this.string(e),this.instanceOf(t,HTMLElement),this.string(r,"Custom error message passed to Assert.hasAttribute needs to be a valid string.");var n=t.getAttribute(e);if(null===n)throw i.expected('html element with attribute "'.concat(e,'"'),t.outerHTML,r)}},{key:"hasAttributes",value:function(e,t){var r=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";this.containsOnlyString(e),this.instanceOf(t,HTMLElement),this.string(n,"Custom error message passed to Assert.hasAttributes needs to be a valid string."),e.map((function(o){try{r.hasAttribute(o,t)}catch(r){throw i.expected('html element with attributes "'.concat(e.join(", "),'"'),t.outerHTML,n)}}))}},{key:"throws",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:new Error;this.isFunction(e);try{e()}catch(e){return"object"===n(e)&&e instanceof Error&&"object"===n(t)&&t instanceof Error?void(t.message.length&&this.equal(e.message,t.message,'Expected exception message "'.concat(e.message,'" to be equals "').concat(t.message,"\" but it's not."))):void this.equal(e,t,"Expected error of type ".concat(s.toString(e)," to be equals ").concat(s.toString(t)," but it's not."))}throw i.expected(s.toString(t),null,'Expected from callback to throw an Error "${expected}" but it didn\'t.')}}],(r=null)&&o(t.prototype,r),a&&o(t,a),e}();e.exports=a},function(e,t,r){"use strict";function n(e,t){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:"";if("string"!=typeof r)throw new Error('Expected string but got "'.concat(i.toString(r),'".'));return r.length?new Error(o.create(r,{expected:e,received:i.toString(t)})):new Error("Expected ".concat(e,' but got "').concat(i.toString(t),'".'))}}],(r=null)&&n(t.prototype,r),s&&n(t,s),e}();e.exports=s},function(e,t,r){"use strict";function n(e){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function o(e,t){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:{};if("string"!=typeof e)throw new Error('Expected string but got "'.concat(ValueConverter.toString(e),'".'));if("object"!==n(t))throw new Error('Expected string but got "'.concat(ValueConverter.toString(t),'".'));return e.replace(i,(function(e,r){return t.hasOwnProperty(r)?t[r]:e}))}}],(r=null)&&o(t.prototype,r),s&&o(t,s),e}();e.exports=s}]);
--------------------------------------------------------------------------------
/bin/es6/assert-js.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var Assert = require('./../../src/AssertJS/Assert');
4 |
5 | module.exports = Assert;
6 |
7 | if (typeof window !== 'undefined') {
8 | window.Assert = Assert;
9 | }
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "assert-js",
3 | "version": "1.0.0",
4 | "description": "Javascript simple assertion library with no dependencies.",
5 | "main": "bin/es5/assert-js.js",
6 | "scripts": {
7 | "test": "node_modules/.bin/madge src/ --circular && node_modules/.bin/mocha --require @babel/register --reporter dot tests/AssertJS --recursive",
8 | "build": "npm run test && node_modules/.bin/babel src --out-dir bin/es5 && node_modules/.bin/webpack --config webpack.config.js",
9 | "prepublishOnly": "npm run build"
10 | },
11 | "repository": {
12 | "type": "git",
13 | "url": "git@github.com:Tiliqua/assert-js.git"
14 | },
15 | "keywords": [
16 | "assertion",
17 | "assert",
18 | "assert-js",
19 | "type hinting",
20 | "es6"
21 | ],
22 | "author": "Norbert Orzechowicz ",
23 | "license": "MIT",
24 | "devDependencies": {
25 | "@babel/cli": "^7.7.7",
26 | "@babel/core": "^7.7.7",
27 | "@babel/preset-env": "^7.7.7",
28 | "@babel/register": "^7.7.7",
29 | "jsdom": "15.2.1",
30 | "madge": "3.6.0",
31 | "mocha": "5.2.0",
32 | "webpack": "4.41.4",
33 | "webpack-cli": "3.3.10"
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/AssertJS/Assert.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | let InvalidValueException = require('./InvalidValueException');
4 | let ValueConverter = require('./ValueConverter');
5 |
6 | class Assert
7 | {
8 | /**
9 | * @param {object} objectValue
10 | * @param {function} expectedInstance
11 | * @param {string} [message]
12 | */
13 | static instanceOf(objectValue, expectedInstance, message = "")
14 | {
15 | this.string(message, "Custom error message passed to Assert.instanceOf needs to be a valid string.");
16 |
17 | if (typeof objectValue !== 'object') {
18 | throw InvalidValueException.expected("object", objectValue, message);
19 | }
20 |
21 | if (!(objectValue instanceof expectedInstance)) {
22 | throw InvalidValueException.expected(
23 | expectedInstance.name,
24 | objectValue,
25 | message.length ? message : "Expected instance of \"${expected}\" but got \"${received}\"."
26 | );
27 | }
28 | }
29 |
30 | static instanceOneOf(objectValue, expectedInstances, message = "")
31 | {
32 | this.string(message, "Custom error message passed to Assert.instanceOf needs to be a valid string.");
33 | this.array(expectedInstances);
34 |
35 | let instance = expectedInstances.find((expectedInstance) => {
36 | return (objectValue instanceof expectedInstance)
37 | });
38 |
39 | if (instance === undefined) {
40 | throw InvalidValueException.expected(
41 | expectedInstances.map((instance) => {return ValueConverter.toString(instance); }).join(', '),
42 | objectValue,
43 | message.length ? message : "Expected instance of \"${expected}\" but got \"${received}\"."
44 | );
45 | }
46 | }
47 |
48 | /**
49 | * @param {int} integerValue
50 | * @param {string} [message]
51 | */
52 | static integer(integerValue, message = "")
53 | {
54 | this.string(message, "Custom error message passed to Assert.integer needs to be a valid string.");
55 |
56 | if (!Number.isInteger(integerValue)) {
57 | throw InvalidValueException.expected("integer", integerValue, message);
58 | }
59 | }
60 |
61 | /**
62 | * @param {number} numberValue
63 | * @param {string} [message]
64 | */
65 | static number(numberValue, message = "")
66 | {
67 | this.string(message, "Custom error message passed to Assert.number needs to be a valid string.");
68 |
69 | if (typeof numberValue !== 'number') {
70 | throw InvalidValueException.expected("number", numberValue);
71 | }
72 | }
73 |
74 | /**
75 | * @param {string} stringValue
76 | * @param {string} [message]
77 | */
78 | static string(stringValue, message = "")
79 | {
80 | if (typeof message !== "string") {
81 | throw new Error("Custom error message passed to Assert.string needs to be a valid string.");
82 | }
83 |
84 | if (typeof stringValue !== "string") {
85 | throw InvalidValueException.expected("string", stringValue, message);
86 | }
87 | }
88 |
89 | /**
90 | * @param {boolean} booleanValue
91 | * @param {string} [message]
92 | */
93 | static boolean(booleanValue, message = "")
94 | {
95 | this.string(message, "Custom error message passed to Assert.boolean needs to be a valid string.");
96 |
97 | if (typeof booleanValue !== 'boolean') {
98 | throw InvalidValueException.expected("boolean", booleanValue, message);
99 | }
100 | }
101 |
102 | /**
103 | * @param {boolean} value
104 | * @param {string} [message]
105 | */
106 | static true(value, message = "")
107 | {
108 | this.boolean(value);
109 | this.string(message, "Custom error message passed to Assert.true needs to be a valid string.");
110 |
111 | if (value !== true) {
112 | throw InvalidValueException.expected("true", value, message);
113 | }
114 | }
115 |
116 | /**
117 | * @param {boolean} value
118 | * @param {string} [message]
119 | */
120 | static false(value, message = "")
121 | {
122 | this.boolean(value);
123 | this.string(message, "Custom error message passed to Assert.false needs to be a valid string.");
124 |
125 | if (value !== false) {
126 | throw InvalidValueException.expected("false", value, message);
127 | }
128 | }
129 |
130 | /**
131 | * @param value
132 | * @param expectedValue
133 | * @param {string} [message]
134 | */
135 | static equal(value, expectedValue, message = "")
136 | {
137 | if (typeof value !== 'object') {
138 | this.true(value === expectedValue, message ? message : `Expected value ${ValueConverter.toString(value)} to be equals ${ValueConverter.toString(expectedValue)} but it's not.`);
139 | } else {
140 | this.objectEqual(value, expectedValue, message ? message : `Expected value ${ValueConverter.toString(value)} to be equals ${ValueConverter.toString(expectedValue)} but it's not.`);
141 | }
142 | }
143 |
144 | /**
145 | * @param {object} object
146 | * @param {object} expectedObject
147 | * @param {string} [message]
148 | */
149 | static objectEqual(object, expectedObject, message = "")
150 | {
151 | this.object(object, message);
152 | this.object(expectedObject, message);
153 |
154 | let objectProperties = Object.getOwnPropertyNames(object);
155 | let expectedObjectProperties = Object.getOwnPropertyNames(expectedObject);
156 |
157 | this.true(objectProperties.length === expectedObjectProperties.length, message ? message : `Expected object ${ValueConverter.toString(object)} to be equals ${ValueConverter.toString(expectedObject)} but it's not.`);
158 |
159 | objectProperties.forEach((objectProperty) => {
160 | this.equal(object[objectProperty], expectedObject[objectProperty], message ? message : `Expected object ${ValueConverter.toString(object)} to be equals ${ValueConverter.toString(expectedObject)} but it's not.`);
161 | });
162 | }
163 |
164 | /**
165 | * @param {object} objectValue
166 | * @param {string} [message]
167 | */
168 | static object(objectValue, message = "")
169 | {
170 | this.string(message, "Custom error message passed to Assert.object needs to be a valid string.");
171 |
172 | if (typeof objectValue !== 'object') {
173 | throw InvalidValueException.expected("object", objectValue, message);
174 | }
175 | }
176 |
177 | /**
178 | * @param {string} expectedFunctionName
179 | * @param {object} objectValue
180 | * @param {string} [message]
181 | */
182 | static hasFunction(expectedFunctionName, objectValue, message = "")
183 | {
184 | this.string(expectedFunctionName);
185 | this.object(objectValue);
186 | this.string(message, "Custom error message passed to Assert.hasFunction needs to be a valid string.");
187 |
188 | if (typeof objectValue[expectedFunctionName] !== 'function') {
189 | throw InvalidValueException.expected(`object to has function "${expectedFunctionName}"`, objectValue, message);
190 | }
191 | }
192 |
193 | /**
194 | * @param {string} expectedPropertyName
195 | * @param {object} objectValue
196 | * @param {string} [message]
197 | */
198 | static hasProperty(expectedPropertyName, objectValue, message = "")
199 | {
200 | this.string(expectedPropertyName);
201 | this.object(objectValue);
202 | this.string(message, "Custom error message passed to Assert.hasProperty needs to be a valid string.");
203 |
204 | if (typeof objectValue[expectedPropertyName] === 'undefined') {
205 | throw InvalidValueException.expected(`object to has property "${expectedPropertyName}"`, objectValue, message);
206 | }
207 | }
208 |
209 | /**
210 | * @param {array} expectedProperties
211 | * @param {object} objectValue
212 | * @param {string} [message]
213 | */
214 | static hasProperties(expectedProperties, objectValue, message = "")
215 | {
216 | this.object(objectValue);
217 | this.containsOnlyString(expectedProperties);
218 | this.string(message, "Custom error message passed to Assert.hasProperties needs to be a valid string.");
219 |
220 | expectedProperties.map((expectedProperty) => {
221 | if (typeof objectValue[expectedProperty] === 'undefined') {
222 | throw InvalidValueException.expected(`object to has properties "${expectedProperties.join(', ')}"`, objectValue, message);
223 | }
224 | });
225 | }
226 |
227 | /**
228 | * @param {array} arrayValue
229 | * @param {string} [message]
230 | */
231 | static array(arrayValue, message = "")
232 | {
233 | this.string(message, "Custom error message passed to Assert.array needs to be a valid string.");
234 |
235 | if (!Array.isArray(arrayValue)) {
236 | throw InvalidValueException.expected("array", arrayValue, message);
237 | }
238 | }
239 |
240 | /**
241 | * @param {*} value
242 | * @param {array} expectedElements
243 | * @param {string} [message]
244 | */
245 | static oneOf(value, expectedElements, message = "")
246 | {
247 | this.string(message, "Custom error message passed to Assert.array needs to be a valid string.");
248 | this.array(expectedElements);
249 |
250 | let foundValue = expectedElements.find((expectedInstance) => {
251 | return value === expectedInstance;
252 | });
253 |
254 | if (foundValue === undefined) {
255 | throw InvalidValueException.expected(
256 | expectedElements.map((elemenet) => {return ValueConverter.toString(elemenet); }).join(', '),
257 | value,
258 | message.length ? message : "Expected one of \"${expected}\" but got \"${received}\"."
259 | );
260 | }
261 | }
262 |
263 | /**
264 | * @param {function} functionValue
265 | * @param {string} [message]
266 | */
267 | static isFunction(functionValue, message = "")
268 | {
269 | this.string(message, "Custom error message passed to Assert.isFunction needs to be a valid string.");
270 |
271 | if (typeof functionValue !== 'function') {
272 | throw InvalidValueException.expected("function", functionValue, message);
273 | }
274 | }
275 |
276 | /**
277 | * @param {int} expected
278 | * @param {int} integerValue
279 | * @param {string} [message]
280 | */
281 | static greaterThan(expected, integerValue, message = "")
282 | {
283 | this.number(expected);
284 | this.number(integerValue);
285 | this.string(message, "Custom error message passed to Assert.greaterThan needs to be a valid string.");
286 |
287 | if (integerValue <= expected) {
288 | throw new Error(message.length > 0 ? message : `Expected value ${integerValue} to be greater than ${expected}`);
289 | }
290 | }
291 |
292 | /**
293 | * @param {int} expected
294 | * @param {int} integerValue
295 | * @param {string} [message]
296 | */
297 | static greaterThanOrEqual(expected, integerValue, message = "")
298 | {
299 | this.number(expected);
300 | this.number(integerValue);
301 | this.string(message, "Custom error message passed to Assert.greaterThanOrEqual needs to be a valid string.");
302 |
303 | if (integerValue < expected) {
304 | throw new Error(message.length > 0 ? message : `Expected value ${integerValue} to be greater than ${expected} or equal`);
305 | }
306 | }
307 |
308 | /**
309 | * @param {int} expected
310 | * @param {int} integerValue
311 | * @param {string} [message]
312 | */
313 | static lessThan(expected, integerValue, message = "")
314 | {
315 | this.number(expected);
316 | this.number(integerValue);
317 | this.string(message, "Custom error message passed to Assert.lessThan needs to be a valid string.");
318 |
319 | if (integerValue >= expected) {
320 | throw new Error(message.length > 0 ? message : `Expected value ${integerValue} to be less than ${expected}`);
321 | }
322 | }
323 |
324 | /**
325 | * @param {int} expected
326 | * @param {int} integerValue
327 | * @param {string} [message]
328 | */
329 | static lessThanOrEqual(expected, integerValue, message = "")
330 | {
331 | this.number(expected);
332 | this.number(integerValue);
333 | this.string(message, "Custom error message passed to Assert.lessThanOrEqual needs to be a valid string.");
334 |
335 | if (integerValue > expected) {
336 | throw new Error(message.length > 0 ? message : `Expected value ${integerValue} to be less than ${expected} or equal`);
337 | }
338 | }
339 |
340 | /**
341 | * @param {array} arrayValue
342 | * @param {function} expectedInstance
343 | * @param {string} [message]
344 | */
345 | static containsOnly(arrayValue, expectedInstance, message = "")
346 | {
347 | this.array(arrayValue, "Assert.containsOnly require valid array, got \"${received}\".");
348 | this.string(message, "Custom error message passed to Assert.containsOnly needs to be a valid string.");
349 |
350 | for (let element of arrayValue) {
351 | try {
352 | this.instanceOf(element, expectedInstance, message);
353 | } catch (error) {
354 | throw InvalidValueException.expected(
355 | expectedInstance.name,
356 | element,
357 | message.length ? message : "Expected instance of \"${expected}\" but got \"${received}\"."
358 | );
359 | }
360 | }
361 | }
362 |
363 | /**
364 | * @param {array} arrayValue
365 | * @param {string} [message]
366 | */
367 | static containsOnlyString(arrayValue, message = "")
368 | {
369 | this.array(arrayValue, "Assert.containsOnlyString require valid array, got \"${received}\".");
370 | this.string(message, "Custom error message passed to Assert.containsOnly needs to be a valid string.");
371 |
372 | for (let element of arrayValue) {
373 | try {
374 | this.string(element, message);
375 | } catch (error) {
376 | throw InvalidValueException.expected(
377 | 'string',
378 | arrayValue.map((value) => { return ValueConverter.toString(value); }).join(', '),
379 | message.length ? message : "Expected array of \"${expected}\" but got \"${received}\"."
380 | );
381 | }
382 | }
383 | }
384 |
385 | /**
386 | * @param {array} arrayValue
387 | * @param {string} [message]
388 | */
389 | static containsOnlyInteger(arrayValue, message = "")
390 | {
391 | this.array(arrayValue, "Assert.containsOnlyInteger require valid array, got \"${received}\".");
392 | this.string(message, "Custom error message passed to Assert.containsOnly needs to be a valid string.");
393 |
394 | for (let element of arrayValue) {
395 | try {
396 | this.integer(element, message);
397 | } catch (error) {
398 | throw InvalidValueException.expected(
399 | 'integer',
400 | arrayValue.map((value) => { return ValueConverter.toString(value); }).join(', '),
401 | message.length ? message : "Expected array of \"${expected}\" but got \"${received}\"."
402 | );
403 | }
404 | }
405 | }
406 |
407 | /**
408 | * @param {array} arrayValue
409 | * @param {string} [message]
410 | */
411 | static containsOnlyNumber(arrayValue, message = "")
412 | {
413 | this.array(arrayValue, "Assert.containsOnlyNumber require valid array, got \"${received}\".");
414 | this.string(message, "Custom error message passed to Assert.containsOnly needs to be a valid string.");
415 |
416 | for (let element of arrayValue) {
417 | try {
418 | this.number(element, message);
419 | } catch (error) {
420 | throw InvalidValueException.expected(
421 | 'number',
422 | arrayValue.map((value) => { return ValueConverter.toString(value); }).join(', '),
423 | message.length ? message : "Expected array of \"${expected}\" but got \"${received}\"."
424 | );
425 | }
426 | }
427 | }
428 |
429 | /**
430 | * @param {int} expectedCount
431 | * @param {array} arrayValue
432 | * @param {string} [message]
433 | */
434 | static count(expectedCount, arrayValue, message = "")
435 | {
436 | this.integer(expectedCount);
437 | this.array(arrayValue);
438 | this.string(message, "Custom error message passed to Assert.count needs to be a valid string.");
439 |
440 | if (arrayValue.length !== expectedCount) {
441 | throw new Error(message.length ? message : `Expected count ${expectedCount}, got ${arrayValue.length}`);
442 | }
443 | }
444 |
445 | /**
446 | * @param {*} value
447 | * @param {string} [message]
448 | */
449 | static notEmpty(value, message = "")
450 | {
451 | this.string(message, "Custom error message passed to Assert.empty needs to be a valid string.");
452 |
453 | if (value.length === 0) {
454 | throw InvalidValueException.expected("not empty value", value, message);
455 | }
456 | }
457 |
458 |
459 | /**
460 | * @param {int} integerValue
461 | * @param {string} [message]
462 | */
463 | static oddNumber(integerValue, message = "")
464 | {
465 | this.integer(integerValue);
466 | this.string(message, "Custom error message passed to Assert.oddNumber needs to be a valid string.");
467 |
468 | if ((integerValue % 2) !== 1) {
469 | throw InvalidValueException.expected("odd number", integerValue, message);
470 | }
471 | }
472 |
473 | /**
474 | * @param {int} integerValue
475 | * @param {string} [message]
476 | */
477 | static evenNumber(integerValue, message = "")
478 | {
479 | this.integer(integerValue);
480 | this.string(message, "Custom error message passed to Assert.evenNumber needs to be a valid string.");
481 |
482 | if ((integerValue % 2) !== 0) {
483 | throw InvalidValueException.expected("even number", integerValue, message);
484 | }
485 | }
486 |
487 | /**
488 | * @param {string} stringValue
489 | * @param {string} [message]
490 | */
491 | static jsonString(stringValue, message = "")
492 | {
493 | this.string(stringValue);
494 | this.string(message, "Custom error message passed to Assert.jsonString needs to be a valid string.");
495 |
496 | try {
497 | JSON.parse(stringValue);
498 | } catch (e) {
499 | throw InvalidValueException.expected("json string", stringValue, message);
500 | }
501 | }
502 |
503 | /**
504 | * @param {string} emailValue
505 | * @param {string} [message]
506 | */
507 | static email(emailValue, message = "")
508 | {
509 | this.string(emailValue);
510 | this.string(message, "Custom error message passed to Assert.email needs to be a valid string.");
511 |
512 | let regexp = /^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i;
513 |
514 | if (!regexp.test(emailValue)) {
515 | throw InvalidValueException.expected("valid email address", emailValue, message);
516 | }
517 | }
518 |
519 | /**
520 | * @param {string} urlValue
521 | * @param {string} [message]
522 | */
523 | static url(urlValue, message = "")
524 | {
525 | this.string(urlValue);
526 | this.string(message, "Custom error message passed to Assert.url needs to be a valid string.");
527 |
528 | let regexp = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/;
529 |
530 | if (!regexp.test(urlValue)) {
531 | throw InvalidValueException.expected("valid url", urlValue, message);
532 | }
533 | }
534 |
535 | /**
536 | * @param {string} uuidValue
537 | * @param {string} [message]
538 | */
539 | static uuid(uuidValue, message = "")
540 | {
541 | this.string(uuidValue);
542 | this.string(message, "Custom error message passed to Assert.uuid needs to be a valid string.");
543 |
544 | let regexp = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
545 |
546 | if (!regexp.test(uuidValue)) {
547 | throw InvalidValueException.expected("valid uuid", uuidValue, message);
548 | }
549 | }
550 |
551 | /**
552 | * @param {string} selector
553 | * @param {HTMLElement|HTMLDocument} htmlElement
554 | * @param {string} [message]
555 | */
556 | static hasElement(selector, htmlElement, message = "")
557 | {
558 | this.string(selector);
559 | this.instanceOneOf(htmlElement, [HTMLElement, HTMLDocument]);
560 | this.string(message, "Custom error message passed to Assert.hasProperty needs to be a valid string.");
561 |
562 | if (null === htmlElement.querySelector(selector)) {
563 | throw InvalidValueException.expected(`html element to has element under selector "${selector}"`, htmlElement.outerHTML, message);
564 | }
565 | }
566 |
567 | /**
568 | * @param {string} attributeName
569 | * @param {HTMLElement} htmlElement
570 | * @param {string} [message]
571 | */
572 | static hasAttribute(attributeName, htmlElement, message = "")
573 | {
574 | this.string(attributeName);
575 | this.instanceOf(htmlElement, HTMLElement);
576 | this.string(message, "Custom error message passed to Assert.hasAttribute needs to be a valid string.");
577 |
578 | let attribute = htmlElement.getAttribute(attributeName);
579 |
580 | if (null === attribute) {
581 | throw InvalidValueException.expected(`html element with attribute "${attributeName}"`, htmlElement.outerHTML, message);
582 | }
583 | }
584 |
585 | /**
586 | * @param {array} attributes
587 | * @param {HTMLElement} htmlElement
588 | * @param {string} [message]
589 | */
590 | static hasAttributes(attributes, htmlElement, message = "")
591 | {
592 | this.containsOnlyString(attributes);
593 | this.instanceOf(htmlElement, HTMLElement);
594 | this.string(message, "Custom error message passed to Assert.hasAttributes needs to be a valid string.");
595 |
596 | attributes.map((attribute) => {
597 | try {
598 | this.hasAttribute(attribute, htmlElement)
599 | } catch (e) {
600 | throw InvalidValueException.expected(`html element with attributes "${attributes.join(', ')}"`, htmlElement.outerHTML, message);
601 | }
602 | })
603 | }
604 |
605 | /**
606 | * @param {function} callback
607 | * @param {object} [expectedError]
608 | */
609 | static throws(callback, expectedError = new Error())
610 | {
611 | this.isFunction(callback);
612 |
613 | try {
614 | callback();
615 | } catch (error) {
616 | if (typeof error === 'object' && error instanceof Error && typeof expectedError === 'object' && expectedError instanceof Error) {
617 |
618 | if (expectedError.message.length) {
619 | this.equal(error.message, expectedError.message, `Expected exception message "${error.message}" to be equals "${expectedError.message}" but it's not.`);
620 | }
621 |
622 | return ;
623 | }
624 |
625 | this.equal(error, expectedError, `Expected error of type ${ValueConverter.toString(error)} to be equals ${ValueConverter.toString(expectedError)} but it's not.`);
626 |
627 | return ;
628 | }
629 |
630 | throw InvalidValueException.expected(
631 | ValueConverter.toString(expectedError),
632 | null,
633 | "Expected from callback to throw an Error \"${expected}\" but it didn't."
634 | );
635 | }
636 | }
637 |
638 | module.exports = Assert;
--------------------------------------------------------------------------------
/src/AssertJS/InvalidValueException.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | let MessageFactory = require('./MessageFactory');
4 | let ValueConverter = require('./ValueConverter');
5 |
6 | class InvalidValueException
7 | {
8 | /**
9 | * @param {string} type
10 | * @param {*} value
11 | * @param {string} [message]
12 | * @returns {Error}
13 | */
14 | static expected(type, value, message = "")
15 | {
16 | if (typeof message !== 'string') {
17 | throw new Error(`Expected string but got "${ValueConverter.toString(message)}".`);
18 | }
19 |
20 | if (message.length) {
21 | return new Error(MessageFactory.create(message, {expected: type, received: ValueConverter.toString(value)}));
22 | }
23 |
24 | return new Error(`Expected ${type} but got "${ValueConverter.toString(value)}".`);
25 | }
26 | }
27 |
28 |
29 | module.exports = InvalidValueException;
--------------------------------------------------------------------------------
/src/AssertJS/MessageFactory.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const VALUE_NAME_REGEXP = /\${(.*?)}/g;
4 |
5 | class MessageFactory
6 | {
7 | /**
8 | * @param {string} template
9 | * @param {object} [data]
10 | */
11 | static create(template, data = {})
12 | {
13 | if (typeof template !== 'string') {
14 | throw new Error(`Expected string but got "${ValueConverter.toString(template)}".`);
15 | }
16 |
17 | if (typeof data !== 'object') {
18 | throw new Error(`Expected string but got "${ValueConverter.toString(data)}".`);
19 | }
20 |
21 | return template.replace(VALUE_NAME_REGEXP, function(placeholder, propertyName) {
22 | if (data.hasOwnProperty(propertyName)) {
23 | return data[propertyName];
24 | }
25 |
26 | return placeholder;
27 | });
28 | }
29 | }
30 |
31 | module.exports = MessageFactory;
--------------------------------------------------------------------------------
/src/AssertJS/ValueConverter.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | class ValueConverter
4 | {
5 | /**
6 | * @param {*} value
7 | * @returns {string}
8 | */
9 | static toString(value)
10 | {
11 | if (typeof value === 'string') {
12 | return `string["${value}"]`;
13 | }
14 |
15 | if (typeof value === 'number') {
16 | if (Number.isInteger(value)) {
17 | return `int[${value}]`;
18 | }
19 |
20 | return `float[${value}]`;
21 | }
22 |
23 | if (typeof value === 'boolean') {
24 | return `boolean[${(value) ? "true" : "false"}]`;
25 | }
26 |
27 | if (typeof value === 'function') {
28 | return `function[${value.toString()}]`;
29 | }
30 |
31 | if (typeof value === 'object') {
32 | if (Array.isArray(value)) {
33 | return `array[length: ${value.length}]`;
34 | }
35 |
36 | if (value instanceof Map) {
37 | return `Map[size: ${value.size}]`;
38 | }
39 |
40 | if (value instanceof WeakMap) {
41 | return `WeakMap[]`;
42 | }
43 |
44 | if (value instanceof Set) {
45 | return `Set[size: ${value.size}]`;
46 | }
47 |
48 | if (value instanceof WeakSet) {
49 | return `WeakSet[]`;
50 | }
51 |
52 | if (value instanceof String) {
53 | return `String["${value}"]`;
54 | }
55 |
56 | if (value instanceof Number) {
57 | let source = value.valueOf();
58 |
59 | if (Number.isInteger(source)) {
60 | return `Number:int[${source}]`;
61 | }
62 |
63 | return `Number:float[${source}]`;
64 | }
65 |
66 | if (value instanceof Boolean) {
67 | return `Boolean[${(value.valueOf()) ? "true" : "false"}]`;
68 | }
69 |
70 | if (value instanceof Date) {
71 | return `Date["${value.toUTCString()}"]`;
72 | }
73 |
74 | if (value instanceof RegExp) {
75 | return `RegExp[${value.toString()}]`;
76 | }
77 |
78 | return `object[${JSON.stringify(value)}]`;
79 | }
80 |
81 | if (typeof value === 'undefined') {
82 | return 'undefined';
83 | }
84 |
85 | throw `Unhandled type ${typeof value}`;
86 | }
87 | }
88 |
89 | module.exports = ValueConverter;
--------------------------------------------------------------------------------
/tests/AssertJS/AssertTest.js:
--------------------------------------------------------------------------------
1 | import jsdom from 'jsdom';
2 | const { JSDOM } = jsdom;
3 | import Assert from '../../bin/es6/assert-js';
4 |
5 | describe("Assert", () => {
6 |
7 | it("compares instance of", () => {
8 | Assert.instanceOf(new String("string"), String);
9 | });
10 |
11 | it("compares instance one of", () => {
12 | Assert.instanceOneOf(new String("string"), [String, Number]);
13 | });
14 |
15 | it ("throws error when asserting instance of non object", () => {
16 | Assert.throws(() => {Assert.instanceOf(1, String)}, new Error('Expected object but got "int[1]".'));
17 | Assert.throws(() => {Assert.instanceOf(new Number(2), String)}, new Error("Expected instance of \"String\" but got \"Number:int[2]\"."));
18 | });
19 |
20 | it ("throws error when custom error message in instanceOf assertion is not valid string", () => {
21 | Assert.throws(
22 | () => {Assert.instanceOf(1, String, new Number(1))},
23 | new Error("Custom error message passed to Assert.instanceOf needs to be a valid string.")
24 | );
25 | });
26 |
27 | it ("throws error when compared different instances", () => {
28 | Assert.throws(() => {Assert.instanceOf(new Number(2), String)}, new Error("Expected instance of \"String\" but got \"Number:int[2]\"."));
29 | Assert.throws(() => {Assert.instanceOf(new Number(2), String, "custom message")}, new Error("custom message"));
30 | });
31 |
32 | it ("throws error when compared all different instances", () => {
33 | Assert.throws(() => {Assert.instanceOneOf(new Number(2), [String, Array] )}, new Error("Expected instance of \"function[function String() { [native code] }], function[function Array() { [native code] }]\" but got \"Number:int[2]\"."));
34 | Assert.throws(() => {Assert.instanceOneOf(new Number(2), [String, Array], "custom message")}, new Error("custom message"));
35 | });
36 |
37 | it ("asserts integers", () => {
38 | Assert.integer(125);
39 | });
40 |
41 | it ("throws error when asserting non integer as an interger", () => {
42 | Assert.throws(() => {Assert.integer("string")}, new Error("Expected integer but got \"string[\"string\"]\"."));
43 | Assert.throws(() => {Assert.integer(new Array([]))}, new Error("Expected integer but got \"array[length: 1]\"."));
44 | Assert.throws(() => {Assert.integer(1.23)}, new Error("Expected integer but got \"float[1.23]\"."));
45 | Assert.throws(() => {Assert.integer(true)}, new Error("Expected integer but got \"boolean[true]\"."));
46 | Assert.throws(() => {Assert.integer(() => {})}, new Error("Expected integer but got \"function[function () {}]\"."));
47 | Assert.throws(() => {Assert.integer(() => {}, "custom message")}, new Error("custom message"));
48 | });
49 |
50 | it ("asserts odd number", () => {
51 | Assert.oddNumber(3);
52 | });
53 |
54 | it ("throws error when asserting non odd number as odd", () => {
55 | Assert.throws(() => {Assert.oddNumber(4)}, new Error("Expected odd number but got \"int[4]\"."));
56 | Assert.throws(() => {Assert.oddNumber(4, "custom message")}, new Error("custom message"));
57 | });
58 |
59 | it ("asserts even number", () => {
60 | Assert.evenNumber(4);
61 | });
62 |
63 | it ("throws error when asserting non even number as even", () => {
64 | Assert.throws(() => {Assert.evenNumber(3)}, new Error("Expected even number but got \"int[3]\"."));
65 | Assert.throws(() => {Assert.evenNumber(3, "custom message")}, new Error("custom message"));
66 | });
67 |
68 | it ("asserts strings", () => {
69 | Assert.string("string");
70 | Assert.string("");
71 | });
72 |
73 | it ("throws error when asserting non string as an string", () => {
74 | Assert.throws(() => {Assert.string(123)}, new Error("Expected string but got \"int[123]\"."));
75 | Assert.throws(() => {Assert.string(new Array([]))}, new Error("Expected string but got \"array[length: 1]\"."));
76 | Assert.throws(() => {Assert.string(1.23)}, new Error("Expected string but got \"float[1.23]\"."));
77 | Assert.throws(() => {Assert.string(true)}, new Error("Expected string but got \"boolean[true]\"."));
78 | Assert.throws(() => {Assert.string(() => {})}, new Error("Expected string but got \"function[function () {}]\"."));
79 | Assert.throws(() => {Assert.string(() => {}, "custom message")}, new Error("custom message"));
80 | });
81 |
82 | it ("throws error when custom message is not valid string", () => {
83 | Assert.throws(() => {Assert.string("", new Number(12))}, new Error("Custom error message passed to Assert.string needs to be a valid string."));
84 | });
85 |
86 | it ("asserts boolean", () => {
87 | Assert.boolean(true);
88 | Assert.boolean(false);
89 | });
90 |
91 | it ("throws error when asserting non boolean as an boolean", () => {
92 | Assert.throws(() => {Assert.boolean(123)}, new Error("Expected boolean but got \"int[123]\"."));
93 | Assert.throws(() => {Assert.boolean(new Array([]))}, new Error("Expected boolean but got \"array[length: 1]\"."));
94 | Assert.throws(() => {Assert.boolean(1.23)}, new Error("Expected boolean but got \"float[1.23]\"."));
95 | Assert.throws(() => {Assert.boolean(() => {})}, new Error("Expected boolean but got \"function[function () {}]\"."));
96 | Assert.throws(() => {Assert.boolean(() => {}, 'custom message')}, new Error("custom message"));
97 | });
98 |
99 | it ("asserts equal values", () => {
100 | Assert.equal(true, true);
101 | Assert.equal(1, 1);
102 | Assert.equal("string", "string");
103 | Assert.equal({"object":1}, {"object":1});
104 | Assert.equal({"object":{"nested":[1,2,3]}}, {"object":{"nested":[1,2,3]}});
105 | Assert.equal([1,2,3], [1,2,3]);
106 | });
107 |
108 | it ("asserts throws error when values are not equal", () => {
109 | Assert.throws(() => {Assert.equal(true, false)}, new Error("Expected value boolean[true] to be equals boolean[false] but it's not."));
110 | Assert.throws(() => {Assert.equal({"object":{"nested":[1,2,3]}}, {"object":{"nested":[3,1,2]}})}, new Error("Expected value object[{\"object\":{\"nested\":[1,2,3]}}] to be equals object[{\"object\":{\"nested\":[3,1,2]}}] but it's not."));
111 | });
112 |
113 | it ("asserts true", () => {
114 | Assert.true(true);
115 | });
116 |
117 | it ("asserts false", () => {
118 | Assert.false(false);
119 | });
120 |
121 | it ("asserts object", () => {
122 | Assert.object({});
123 | Assert.object(new String("test"));
124 | });
125 |
126 | it ("throws error when asserting non object as an object", () => {
127 | Assert.throws(() => {Assert.object(123)}, new Error("Expected object but got \"int[123]\"."));
128 | Assert.throws(() => {Assert.object(1.23)}, new Error("Expected object but got \"float[1.23]\"."));
129 | Assert.throws(() => {Assert.object(() => {})}, new Error("Expected object but got \"function[function () {}]\"."));
130 | Assert.throws(() => {Assert.object(() => {}, 'custom message')}, new Error("custom message"));
131 | });
132 |
133 | it ("asserts has function on anonymous object", () => {
134 | Assert.hasFunction("test", {test: () => {}});
135 | });
136 |
137 | it ("asserts has function on object", () => {
138 | Assert.hasFunction("concat", new String("test"));
139 | });
140 |
141 | it ("throws error when asserting that object has function that he does not have", () => {
142 | Assert.throws(() => {Assert.hasFunction("test", new String("test"))}, new Error("Expected object to has function \"test\" but got \"String[\"test\"]\"."));
143 | Assert.throws(() => {Assert.hasFunction("test", new String("test"), "custom message")}, new Error("custom message"));
144 | });
145 |
146 | it ("asserts has property on anonymous object", () => {
147 | Assert.hasProperty("test", {test: 'value'});
148 | });
149 |
150 | it ("asserts has property on object", () => {
151 | class MyObject {
152 | constructor()
153 | {
154 | this.test = 'test';
155 | }
156 | }
157 | Assert.hasProperty("test", new MyObject());
158 | });
159 |
160 | it ("throws error when asserting that object has property that he does not have", () => {
161 | Assert.throws(() => {Assert.hasProperty("test", new String("test"))}, new Error("Expected object to has property \"test\" but got \"String[\"test\"]\"."));
162 | Assert.throws(() => {Assert.hasProperty("test", new String("test"), "custom message")}, new Error("custom message"));
163 | });
164 |
165 | it ("asserts has properties on anonymous object", () => {
166 | Assert.hasProperties(['test', 'foo', 'bar'], {test: 'value', foo: 'foo', bar: 'bar'});
167 | });
168 |
169 | it ("asserts has properties on object", () => {
170 | class MyObject {
171 | constructor()
172 | {
173 | this.test = 'test';
174 | this.foo = 'for';
175 | this.bar = 'bar';
176 | }
177 | }
178 | Assert.hasProperties(['test', 'foo', 'bar'], new MyObject());
179 | });
180 |
181 | it ("throws error when asserting that object has properties that he does not have", () => {
182 | Assert.throws(() => {Assert.hasProperties(["test", "foo"], new String("test"))}, new Error("Expected object to has properties \"test, foo\" but got \"String[\"test\"]\"."));
183 | Assert.throws(() => {Assert.hasProperties(["test", "foo"], new String("test"), "custom message")}, new Error("custom message"));
184 | });
185 |
186 | it ("asserts function", () => {
187 | Assert.isFunction(() => {});
188 | });
189 |
190 | it ("throws error when asserting non function as an function", () => {
191 | Assert.throws(() => {Assert.isFunction(123)}, new Error("Expected function but got \"int[123]\"."));
192 | Assert.throws(() => {Assert.isFunction(new Array([]))}, new Error("Expected function but got \"array[length: 1]\"."));
193 | Assert.throws(() => {Assert.isFunction(1.23)}, new Error("Expected function but got \"float[1.23]\"."));
194 | Assert.throws(() => {Assert.isFunction(1.23, 'custom message')}, new Error("custom message"));
195 | });
196 |
197 | it ("asserts values greater than", () => {
198 | Assert.greaterThan(10, 120);
199 | });
200 |
201 | it ("throws error when asserting value lower than", () => {
202 | Assert.throws(() => {Assert.greaterThan(10, 1)}, new Error("Expected value 1 to be greater than 10"));
203 | Assert.throws(() => {Assert.greaterThan(10, 1, 'custom message')}, new Error("custom message"));
204 | });
205 |
206 | it ("asserts values greater than or equal", () => {
207 | Assert.greaterThanOrEqual(10, 10);
208 | });
209 |
210 | it ("throws error when asserting value less than or equal", () => {
211 | Assert.throws(() => {Assert.greaterThanOrEqual(10, 1)}, new Error("Expected value 1 to be greater than 10 or equal"));
212 | Assert.throws(() => {Assert.greaterThanOrEqual(10, 1, 'custom message')}, new Error("custom message"));
213 | });
214 |
215 | it ("asserts values less than", () => {
216 | Assert.lessThan(10, 1);
217 | });
218 |
219 | it ("throws error when asserting value greater than", () => {
220 | Assert.throws(() => {Assert.lessThan(10, 100)}, new Error("Expected value 100 to be less than 10"));
221 | Assert.throws(() => {Assert.lessThan(10, 100, 'custom message')}, new Error("custom message"));
222 | });
223 |
224 | it ("asserts values less than or equal", () => {
225 | Assert.lessThanOrEqual(10, 10);
226 | });
227 |
228 | it ("throws error when asserting value greater than or equal", () => {
229 | Assert.throws(() => {Assert.lessThanOrEqual(10, 100)}, new Error("Expected value 100 to be less than 10 or equal"));
230 | Assert.throws(() => {Assert.lessThanOrEqual(10, 100, 'custom message')}, new Error("custom message"));
231 | });
232 |
233 | it ("asserts array", () => {
234 | Assert.array(new Array(5));
235 | Assert.array(['test1', 'test2']);
236 | });
237 |
238 | it ("throws error when asserting non array value as array", () => {
239 | Assert.throws(() => {Assert.array(123)}, new Error("Expected array but got \"int[123]\"."));
240 | Assert.throws(() => {Assert.array(123, 'custom message')}, new Error("custom message"));
241 | });
242 |
243 | it ("asserts one of", () => {
244 | Assert.oneOf(1, [2, 5, 6, 1]);
245 | Assert.oneOf('a', ['b', 'a', 'c']);
246 | });
247 |
248 | it ("throws error when asserting that element is non of expected", () => {
249 | Assert.throws(() => {Assert.oneOf('z', ['b', 'a', 'c'])}, new Error("Expected one of \"string[\"b\"], string[\"a\"], string[\"c\"]\" but got \"string[\"z\"]\"."));
250 | Assert.throws(() => {Assert.oneOf('z', ['b', 'a', 'c'], 'custom message')}, new Error("custom message"));
251 | });
252 |
253 | it ("asserts contains only specific instances in array", () => {
254 | Assert.containsOnly(
255 | [
256 | new String("test"),
257 | new String("test1")
258 | ],
259 | String
260 | );
261 | });
262 |
263 | it ("throws error when contains only does not assert on array", () => {
264 | Assert.throws(() => {Assert.containsOnly(123)}, new Error("Assert.containsOnly require valid array, got \"int[123]\"."));
265 | });
266 |
267 | it ("throws error when contains only has at least one non object element", () => {
268 | Assert.throws(() => {Assert.containsOnly([new String("test"), 132], String)}, new Error("Expected instance of \"String\" but got \"int[132]\"."));
269 | Assert.throws(() => {Assert.containsOnly([new String("test"), 132], String, 'custom message')}, new Error("custom message"));
270 | });
271 |
272 | it ("throws error when contains only has at least one non expected instance element", () => {
273 | Assert.throws(() => {Assert.containsOnly([new String("test"), new Number(23)], String)}, new Error("Expected instance of \"String\" but got \"Number:int[23]\"."));
274 | });
275 |
276 | it ("asserts contains only strings in array", () => {
277 | Assert.containsOnlyString(["test", "test1"]);
278 | });
279 |
280 | it ("asserts contains only integers in array", () => {
281 | Assert.containsOnlyInteger([1, 2]);
282 | });
283 |
284 | it ("asserts contains only numbers in array", () => {
285 | Assert.containsOnlyNumber([2, 10.25]);
286 | });
287 |
288 | it ("throws error when contains only strings has at least one non string element", () => {
289 | Assert.throws(() => {Assert.containsOnlyString([132, "test"])}, new Error("Expected array of \"string\" but got \"string[\"int[132], string[\"test\"]\"]\"."));
290 | Assert.throws(() => {Assert.containsOnlyString([132, "test"], 'custom message')}, new Error("custom message"));
291 | });
292 |
293 | it ("throws error when contains only integers has at least one non integer element", () => {
294 | Assert.throws(() => {Assert.containsOnlyInteger([132, "test"])}, new Error("Expected array of \"integer\" but got \"string[\"int[132], string[\"test\"]\"]\"."));
295 | Assert.throws(() => {Assert.containsOnlyInteger([132, "test"], 'custom message')}, new Error("custom message"));
296 | });
297 |
298 | it ("throws error when contains only numbers has at least one non number element", () => {
299 | Assert.throws(() => {Assert.containsOnlyNumber([132, "test"])}, new Error("Expected array of \"number\" but got \"string[\"int[132], string[\"test\"]\"]\"."));
300 | Assert.throws(() => {Assert.containsOnlyNumber([132, "test"], 'custom message')}, new Error("custom message"));
301 | });
302 |
303 | it ("asserts array count", () => {
304 | Assert.count(
305 | 2,
306 | [
307 | new String("test"),
308 | new String("test1")
309 | ]
310 | );
311 | });
312 |
313 | it ("throws error when expected count different than array count", () => {
314 | Assert.throws(() => {Assert.count(3, [new String("test")])}, new Error("Expected count 3, got 1"));
315 | Assert.throws(() => {Assert.count(3, [new String("test")], 'custom message')}, new Error("custom message"));
316 | });
317 |
318 | it ("asserts not empty value", () => {
319 | Assert.notEmpty("test");
320 | });
321 |
322 | it ("throws error when asserting empty string as non empty value", () => {
323 | Assert.throws(() => {Assert.notEmpty("")}, new Error("Expected not empty value but got \"string[\"\"]\"."));
324 | Assert.throws(() => {Assert.notEmpty("", 'custom message')}, new Error("custom message"));
325 | });
326 |
327 | it ("asserts json string", () => {
328 | Assert.jsonString('{"key":"value"}');
329 | });
330 |
331 | it ("throws error when expected json string is not valid", () => {
332 | Assert.throws(() => {Assert.jsonString('{"key":value"}')}, new Error("Expected json string but got \"string[\"{\"key\":value\"}\"]\"."));
333 | Assert.throws(() => {Assert.jsonString('{"key":value"}', "custom message")}, new Error("custom message"));
334 | });
335 |
336 | it ("asserts email", () => {
337 | Assert.email('norbert@orzechowicz.pl');
338 | });
339 |
340 | it ("throws error when email is not valid", () => {
341 | Assert.throws(() => {Assert.email('not_valid_email@com')}, new Error("Expected valid email address but got \"string[\"not_valid_email@com\"]\"."));
342 | Assert.throws(() => {Assert.email('not_valid_email@com', "custom message")}, new Error("custom message"));
343 | });
344 |
345 | it ("asserts url", () => {
346 | Assert.url('http://foo.com/blah_blah');
347 | Assert.url('http://foo.com/blah_blah/');
348 | Assert.url('http://foo.com/blah_blah_(wikipedia)');
349 | Assert.url('http://foo.com/blah_blah_(wikipedia)_(again)');
350 | Assert.url('http://www.example.com/wpstyle/?p=364');
351 | Assert.url('https://www.example.com/foo/?bar=baz&inga=42&quux');
352 | Assert.url('http://userid:password@example.com:8080');
353 | Assert.url('http://userid:password@example.com:8080/');
354 | Assert.url('http://userid@example.com');
355 | Assert.url('http://userid@example.com/');
356 | Assert.url('http://userid@example.com:8080/');
357 | Assert.url('http://userid:password@example.com');
358 | Assert.url('http://userid:password@example.com/');
359 | Assert.url('http://142.42.1.1/');
360 | Assert.url('http://192.168.0.1:8000');
361 | Assert.url('http://127.0.0.1:8000');
362 | Assert.url('http://localhost:8000');
363 | Assert.url('http://localhost');
364 | Assert.url('http://foo.com/blah_(wikipedia)#cite-1');
365 | Assert.url('http://foo.com/unicode_(✪)_in_parens');
366 | });
367 |
368 | it ("throws error when url is not valid", () => {
369 | Assert.throws(() => {Assert.url('http://')}, new Error("Expected valid url but got \"string[\"http://\"]\"."));
370 | Assert.throws(() => {Assert.url('http://', "custom message")}, new Error("custom message"));
371 | });
372 |
373 | it ("asserts uuid", () => {
374 | Assert.uuid('5e8a2b26-1479-11e6-a148-3e1d05defe78'); // version 1
375 | Assert.uuid('386f9c10-d886-49b4-8153-ba1873c684ed'); // version 4
376 | });
377 |
378 | it ("throws error when uuid is not valid", () => {
379 | Assert.throws(() => {Assert.uuid('1234567890')}, new Error("Expected valid uuid but got \"string[\"1234567890\"]\"."));
380 | Assert.throws(() => {Assert.uuid('1234567890', "custom message")}, new Error("custom message"));
381 | });
382 |
383 | it ("asserts that document element exists under selector of HTMLDocument", () => {
384 | let dom = new JSDOM(``);
385 |
386 | global.HTMLDocument = dom.window.HTMLDocument;
387 | global.HTMLElement = dom.window.HTMLElement;
388 |
389 | Assert.hasElement('#div', dom.window.document);
390 | });
391 |
392 | it ("asserts that document element exists under selector of HTMLElement", () => {
393 | let dom = new JSDOM(``);
394 |
395 | global.HTMLDocument = dom.window.HTMLDocument;
396 | global.HTMLElement = dom.window.HTMLElement;
397 |
398 | Assert.hasElement('#div', dom.window.document.body);
399 | });
400 |
401 | it ("throws exception when document element does not exists under selector", () => {
402 | let dom = new JSDOM(``);
403 |
404 | global.HTMLDocument = dom.window.HTMLDocument;
405 | global.HTMLElement = dom.window.HTMLElement;
406 |
407 | Assert.throws(() => {Assert.hasElement('#not-exists', dom.window.document.body)}, new Error("Expected html element to has element under selector \"#not-exists\" but got \"string[\"\"]\"."));
408 | });
409 |
410 | it ("asserts that html element has data attribute", () => {
411 | let dom = new JSDOM(``);
412 |
413 | global.HTMLElement = dom.window.HTMLElement;
414 |
415 | Assert.hasAttribute('data-test', dom.window.document.querySelector('#test'));
416 | });
417 |
418 | it ("asserts that html element has attribute", () => {
419 | let dom = new JSDOM(``);
420 |
421 | global.HTMLElement = dom.window.HTMLElement;
422 |
423 | Assert.hasAttribute('id', dom.window.document.querySelector('#test'));
424 | });
425 |
426 | it ("throws exception when html element does not have data attribute", () => {
427 | let dom = new JSDOM(``);
428 |
429 | global.HTMLElement = dom.window.HTMLElement;
430 |
431 | Assert.throws(() => {Assert.hasAttribute('data-foo', dom.window.document.querySelector('#test'))}, new Error("Expected html element with attribute \"data-foo\" but got \"string[\"\"]\"."));
432 | });
433 |
434 | it ("asserts that html element has multiple attributes", () => {
435 | let dom = new JSDOM(``);
436 |
437 | global.HTMLElement = dom.window.HTMLElement;
438 |
439 | Assert.hasAttributes(['id', 'data-test'], dom.window.document.querySelector('#test'));
440 | });
441 |
442 | it ("throws exception when html element does not have data attribute", () => {
443 | let dom = new JSDOM(``);
444 |
445 | global.HTMLElement = dom.window.HTMLElement;
446 |
447 | Assert.throws(() => {Assert.hasAttributes(['data-foo', 'bar'], dom.window.document.querySelector('#test'))}, new Error("Expected html element with attributes \"data-foo, bar\" but got \"string[\"\"]\"."));
448 | });
449 |
450 | it ("throws exception when callback is not throwing expected exception", () => {
451 | Assert.throws(
452 | () => {
453 | Assert.throws(
454 | () => {
455 | // do nothing
456 | },
457 | new Error('Expected error message'),
458 | )
459 | },
460 | new Error("Expected from callback to throw an Error \"object[{}]\" but it didn't.")
461 | );
462 | });
463 |
464 | it ("throws exception when callback is not throwing expected exception type", () => {
465 | Assert.throws(
466 | () => {
467 | Assert.throws(
468 | () => {
469 | throw 'test';
470 | },
471 | new Error('test')
472 | )
473 | },
474 | new Error("Expected error of type string[\"test\"] to be equals object[{}] but it's not.")
475 | );
476 | });
477 |
478 | it ("throws exception when error message is different than expected but type matches", () => {
479 | Assert.throws(
480 | () => {
481 | Assert.throws(
482 | () => {
483 | throw new Error('unexpected message');
484 | },
485 | new Error('expected message')
486 | )
487 | },
488 | new Error("Expected exception message \"unexpected message\" to be equals \"expected message\" but it's not.")
489 | );
490 | });
491 |
492 | it ("throws exception when error type is different than expected error type", () => {
493 | Assert.throws(
494 | () => {
495 | Assert.throws(
496 | () => {
497 | throw new String('expected message');
498 | },
499 | new Error('expected message')
500 | )
501 | },
502 | new Error("Expected error of type String[\"expected message\"] to be equals object[{}] but it's not.")
503 | );
504 | });
505 |
506 | it ("asserts that thrown errors are the same", () => {
507 | Assert.throws(() => { throw new String('expected message'); }, new String('expected message'));
508 | Assert.throws(() => { throw 'expected message'; }, 'expected message');
509 | Assert.throws(() => { throw new Error(); });
510 | Assert.throws(() => { throw new Error('some not relevant error message'); }, new Error());
511 | Assert.throws(() => { throw new Error('some relevant error message'); }, new Error('some relevant error message'));
512 | });
513 | });
--------------------------------------------------------------------------------
/tests/AssertJS/MessageFactoryTest.js:
--------------------------------------------------------------------------------
1 | import MessageFactory from '../../src/AssertJS/MessageFactory';
2 | import Assert from '../../src/AssertJS/Assert'
3 |
4 | describe("MessageFactory", () => {
5 | it("builds message from template using es6 template syntax ", () => {
6 | Assert.equal(MessageFactory.create("this is ${test}", {test: "value"}), "this is value");
7 | });
8 |
9 | it("ignores placeholder that are missing values", () => {
10 | Assert.equal(MessageFactory.create("this is ${test}", {foo: "value"}),"this is ${test}");
11 | });
12 |
13 | it("builds template from multiple placeholders", () => {
14 | Assert.equal(
15 | MessageFactory.create("this is ${foo} and this is ${bar}", {foo: "foo1", bar: "bar1"}),
16 | "this is foo1 and this is bar1"
17 | );
18 | });
19 | });
--------------------------------------------------------------------------------
/tests/AssertJS/ValueConverterTest.js:
--------------------------------------------------------------------------------
1 | import ValueConverter from '../../src/AssertJS/ValueConverter';
2 | import Assert from '../../src/AssertJS/Assert';
3 |
4 | describe("ValueConverter", () => {
5 | it("casts native string value to string", () => {
6 | Assert.equal(ValueConverter.toString("string"), "string[\"string\"]");
7 | });
8 |
9 | it("casts native integer value to string", () => {
10 | Assert.equal(ValueConverter.toString(1), "int[1]");
11 | });
12 |
13 | it("casts native negative integer value to string", () => {
14 | Assert.equal(ValueConverter.toString(-11), "int[-11]");
15 | });
16 |
17 | it("casts native float value to string", () => {
18 | Assert.equal(ValueConverter.toString(1.24), "float[1.24]");
19 | });
20 |
21 | it("casts native array value to string", () => {
22 | Assert.equal(ValueConverter.toString([1, 2, 3, 4, 5]), "array[length: 5]");
23 | });
24 |
25 | it("casts native negative float value to string", () => {
26 | Assert.equal(ValueConverter.toString(-1.24), "float[-1.24]");
27 | });
28 |
29 | it("casts native boolean value to string", () => {
30 | Assert.equal(ValueConverter.toString(true), "boolean[true]");
31 | Assert.equal(ValueConverter.toString(false), "boolean[false]");
32 | });
33 |
34 | it("casts native regexp value to string", () => {
35 | Assert.equal(ValueConverter.toString(/ab+c/), "RegExp[/ab+c/]");
36 | });
37 |
38 | it("casts native String object value to string", () => {
39 | Assert.equal(ValueConverter.toString(new String("string")), "String[\"string\"]");
40 | });
41 |
42 | it("casts native Number integer object value to string", () => {
43 | Assert.equal(ValueConverter.toString(new Number(1)), "Number:int[1]");
44 | });
45 |
46 | it("casts native Number negative integer object value to string", () => {
47 | Assert.equal(ValueConverter.toString(new Number(-1)), "Number:int[-1]");
48 | });
49 |
50 | it("casts native Number negative float object value to string", () => {
51 | Assert.equal(ValueConverter.toString(new Number(-1.25)), "Number:float[-1.25]");
52 | });
53 |
54 | it("casts native Number float object value to string", () => {
55 | Assert.equal(ValueConverter.toString(new Number(2.42)), "Number:float[2.42]");
56 | });
57 |
58 | it("casts native Boolean object value to string", () => {
59 | Assert.equal(ValueConverter.toString(new Boolean(true)), "Boolean[true]");
60 | Assert.equal(ValueConverter.toString(new Boolean(false)), "Boolean[false]");
61 | });
62 |
63 | it("casts native Date object value to string", () => {
64 | Assert.equal(ValueConverter.toString(new Date(Date.UTC(2015, 1, 10, 0, 0, 0))), "Date[\"Tue, 10 Feb 2015 00:00:00 GMT\"]");
65 | });
66 |
67 | it("casts native RegExp object value to string", () => {
68 | Assert.equal(ValueConverter.toString(new RegExp('ab+c')), "RegExp[/ab+c/]");
69 | });
70 |
71 | it("casts native Array object value to string", () => {
72 | Assert.equal(ValueConverter.toString(new Array()), "array[length: 0]");
73 | });
74 |
75 | it("casts native Map object value to string", () => {
76 | Assert.equal(ValueConverter.toString(new Map()), "Map[size: 0]");
77 | });
78 |
79 | it("casts native WeakMap object value to string", () => {
80 | Assert.equal(ValueConverter.toString(new WeakMap()), "WeakMap[]");
81 | });
82 |
83 | it("casts native Set object value to string", () => {
84 | Assert.equal(ValueConverter.toString(new Set()), "Set[size: 0]");
85 | });
86 |
87 | it("casts native WeakSet object value to string", () => {
88 | Assert.equal(ValueConverter.toString(new WeakSet()), "WeakSet[]");
89 | });
90 |
91 | it("casts simple objects value to string", () => {
92 | Assert.equal(ValueConverter.toString({id: 1, name: "test"}), `object[{"id":1,"name":"test"}]`);
93 | });
94 |
95 | it("casts function value to string", () => {
96 | Assert.equal(ValueConverter.toString((arg) => {}), `function[function (arg) {}]`);
97 | });
98 | });
--------------------------------------------------------------------------------
/webpack.config.js:
--------------------------------------------------------------------------------
1 | var webpack = require('webpack');
2 |
3 | module.exports = {
4 | entry: __dirname + "/bin/es5/assert-js.js",
5 | mode: "production",
6 | output: {
7 | filename: "assert-js.min.js",
8 | path: __dirname + "/bin/es5/",
9 | },
10 | optimization: {
11 | minimize: true
12 | }
13 | };
14 |
--------------------------------------------------------------------------------