utilities/test/index.js

103 lines
2.2 KiB
JavaScript
Raw Normal View History

2020-03-04 13:31:32 +01:00
/*
* Copyright (C) Sapphirecode - All Rights Reserved
* This file is part of utilities which is released under MIT.
2020-03-25 17:01:22 +01:00
* See file 'LICENSE' for full license details.
* Created by Timo Hocker <timo@scode.ovh>, May 2020
2020-03-04 13:31:32 +01:00
*/
/* eslint-disable no-magic-numbers */
// @ts-nocheck
'use strict';
const test = require ('ava');
const util = require ('../index');
test ('truncate_decimal', (t) => {
const trunc = util.truncate_decimal (1.23456, 2);
t.is (trunc, 1.23);
});
test ('try_parse_json should parse', (t) => {
const str = '{"test":"foo"}';
t.notThrows (() => {
const json = util.try_parse_json (str);
t.deepEqual (json, { test: 'foo' });
});
});
test ('try_parse_json should fail', (t) => {
const str = '{"test":foo"}';
t.notThrows (() => {
const json = util.try_parse_json (str);
t.is (json, null);
});
});
2020-03-10 10:46:12 +01:00
test ('copy object', (t) => {
2020-03-10 10:51:01 +01:00
const obj = { foo: 'bar' };
const copy = util.copy_object (obj);
2020-03-10 10:46:12 +01:00
copy.foo = 'baz';
2020-03-10 10:51:01 +01:00
t.is (copy.foo, 'baz');
t.is (obj.foo, 'bar');
2020-03-10 10:46:12 +01:00
});
2020-03-30 11:10:29 +02:00
test ('run regex', (t) => {
const data = 'foobarfoo';
const regex = /foo/gu;
let count = 0;
2020-03-30 11:21:05 +02:00
util.run_regex (regex, data, (res) => {
t.is (res[0], 'foo');
2020-03-30 11:10:29 +02:00
count++;
2020-03-30 11:21:05 +02:00
});
t.is (count, 2);
});
test ('run non-global regex', (t) => {
const data = 'foobarfoo';
const regex = /foo/u;
let count = 0;
util.run_regex (regex, data, (res) => {
t.is (res[0], 'foo');
count++;
});
t.is (count, 1);
});
test ('run non-global regex without result', (t) => {
const data = 'foobarfoo';
const regex = /baz/u;
let count = 0;
2020-03-30 14:09:23 +02:00
util.run_regex (regex, data, () => {
2020-03-30 11:21:05 +02:00
count++;
});
t.is (count, 0);
2020-03-30 11:10:29 +02:00
});
2020-04-28 08:27:06 +02:00
test ('check isnil with undefined', (t) => {
t.is (util.is_nil (), true);
});
test ('check isnil with null', (t) => {
t.is (util.is_nil (null), true);
});
test ('check isnil with empty string', (t) => {
t.is (util.is_nil (''), false);
});
test ('check isnil with string', (t) => {
t.is (util.is_nil ('foo'), false);
});
test ('check isnil with 0', (t) => {
t.is (util.is_nil (0), false);
});
test ('check isnil with nan', (t) => {
t.is (util.is_nil (parseInt ('foo')), true);
});
test ('check isnil with int', (t) => {
t.is (util.is_nil (parseInt ('42')), false);
});