Compare commits

..

36 Commits

Author SHA1 Message Date
Geoff Doty 1bf0aab37e deps & shorter fn syntax 2025-03-24 19:46:45 -04:00
Geoff Doty a71500e31f npm compat 2024-06-16 16:11:39 -04:00
Geoff Doty a6948f9b37 update deps 2024-06-16 16:04:12 -04:00
Geoff Doty efa77cf804
Merge pull request #3 from n2geoff/dependabot/npm_and_yarn/word-wrap-1.2.4
Bump word-wrap from 1.2.3 to 1.2.4
2024-03-02 07:02:10 -06:00
dependabot[bot] 539c71f107
Bump word-wrap from 1.2.3 to 1.2.4
Bumps [word-wrap](https://github.com/jonschlinkert/word-wrap) from 1.2.3 to 1.2.4.
- [Release notes](https://github.com/jonschlinkert/word-wrap/releases)
- [Commits](https://github.com/jonschlinkert/word-wrap/compare/1.2.3...1.2.4)

---
updated-dependencies:
- dependency-name: word-wrap
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-19 20:07:23 +00:00
Geoff Doty ac5626cd25 deps 2023-03-15 09:54:36 -04:00
Geoff Doty 0112677df5 npm package naming woes 2022-07-31 11:55:26 -04:00
Geoff Doty 07daa67faf rename for npm 2022-07-31 11:50:54 -04:00
Geoff Doty 0bc6300cbc 1.1.1 2022-07-31 11:48:00 -04:00
Geoff Doty bd7c4e25fa rename package for npm 2022-07-31 11:47:52 -04:00
Geoff Doty 08e4364aea 1.1.0 2022-07-31 01:50:15 -04:00
Geoff Doty 9846dbb618 remove live-server as dep, but call via npx if requested 2022-07-31 01:49:50 -04:00
Geoff Doty 8d880193a5 linting 2022-07-31 01:40:35 -04:00
Geoff Doty 98c7523881 switching to esbuild 2021-01-02 03:42:41 -05:00
Geoff Doty 12233bfb6c update deps 2021-01-01 15:57:07 -05:00
Geoff Doty c99bd20059 bump version 2020-09-20 16:02:45 -04:00
Geoff Doty 7444e0abcc leverage live-server for test runner 2020-09-20 15:59:30 -04:00
Geoff Doty cacc7a5d33 replace expect with simpler assert 2020-09-20 15:58:00 -04:00
Geoff Doty 7e268c6303 fix lock file issue 2020-09-20 14:04:59 -04:00
Geoff Doty 0aa72d399b update dist 2020-09-08 17:37:54 -05:00
Geoff Doty 85a491ce98 changed how testit is self tested 2020-09-08 17:37:24 -05:00
Geoff Doty ec4e087e90 convert to rollup build system 2020-09-08 17:29:56 -05:00
Geoff Doty 1a388656f2 replace jshint w/ eslint 2020-09-08 17:27:17 -05:00
Geoff Doty 2be7350902 0.8.2 2020-09-08 12:09:13 -05:00
Geoff Doty 4b59b2394b FIX: Audit Warning 2020-09-08 12:09:08 -05:00
Geoff Doty 75d3782aaf updated dev deps 2020-05-27 16:34:09 -05:00
Geoff Doty f28f550cd4 updated deps 2019-08-14 13:08:24 -05:00
Geoff Doty b5680387c4 formatting tweaks 2019-01-13 17:09:21 -05:00
Geoff Doty f38a7fe295 docs & comments 2019-01-13 16:47:55 -05:00
Geoff Doty b1bd8bf47d added to.be.ok() shorthand 2019-01-13 16:47:12 -05:00
Geoff Doty e25707b493 updated deps 2019-01-13 16:44:13 -05:00
Geoff Doty c1d8f386eb added way to supress error stack 2018-12-02 04:30:08 -05:00
Geoff Doty c4cf2ed933 updated output format 2018-12-02 03:43:35 -05:00
Geoff Doty e72a99fec1 contrib fixes 2018-12-02 03:40:30 -05:00
Geoff Doty 6c437a619e named functions on core methods 2018-11-09 11:21:58 -05:00
Geoff Doty 18e11a4842 bump src version to match 2018-11-09 11:03:08 -05:00
17 changed files with 1146 additions and 5022 deletions

View File

@ -1,3 +0,0 @@
{
"esversion": 6
}

View File

@ -1,6 +1,6 @@
# Contributing # Contributing
So you want to contribute, nice. **Thank you**. So you want to contribute, awesome. **Thank you**.
Bug reports and code and documentation patches are all welcome. You can help this project also by using the development version and by reporting any bugs you might encounter. Bug reports and code and documentation patches are all welcome. You can help this project also by using the development version and by reporting any bugs you might encounter.
@ -33,12 +33,12 @@ The `dist` includes the minified version of the source code.
Run unit tests using this command: Run unit tests using this command:
```bash ```bash
npm test npm run test
``` ```
## Reporting a bug ## Reporting a bug
Use the [GitHub issue tracker](https://github.com/n2geoff/js-lib/issues) to report any bug you find. Use the [GitHub issue tracker](https://github.com/n2geoff/testit/issues/new) to report any bug you find.
Bugs description should include: Bugs description should include:
* How to reproduce the bug; * How to reproduce the bug;
@ -48,11 +48,9 @@ Would be nice to have some code showing how to reproduce the code, you may use [
## Request a feature ## Request a feature
Use the [GitHub issue tracker](https://github.com/n2geoff/js-lib/issues) to request a new feature. Use the [GitHub issue tracker](https://github.com/n2geoff/testit/issues/new) to request a new feature.
Keep in mind, this is a pure javascript library Keep in mind, this is a pure javascript library, no dependencies as minimal as possible
Feel free to port it to your favorite framework, such as [RiotJS](http://riotjs.com), Angular or VueJs in a new repository.
## Commit message ## Commit message

View File

@ -1,6 +1,6 @@
The MIT License The MIT License
Copyright (c) 2018 testit authors Copyright (c) 2023 Geoff Doty
Permission is hereby granted, free of charge, to any person obtaining a copy of Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in this software and associated documentation files (the "Software"), to deal in

View File

@ -1,39 +1,41 @@
# Test.it # Test.it
> A minimalistic testing library > A minimalistic client-side testing library
**Test.it** is a small testing library for people that want to live in code, not in tests. No over engineering here. Inspired by the simplicity of libraries like [Tape](https://github.com/substack/tape),but the implementation ideas of things like [Expect](https://github.com/Automattic/expect.js) and [TinyTest](https://github.com/joewalnes/jstinytest) **Test.it** is a small client-side testing library for people that want to live in code, not in tests. No over engineering here. Inspired by the simplicity of libraries like [Jasmine](https://jasmine.github.io/), but implementation ideas based on [TinyTest](https://github.com/joewalnes/jstinytest)
This is probally not a *cure-all* testing solution, if you want something more robust checkout [Jasmine](), [Tape]() or [Mocha]() -- this is to... This is probally not a *cure-all* testing solution, if you want something more robust checkout [Jasmine](https://jasmine.github.io/), [Tape](https://github.com/substack/tape) or [Mocha](https://mochajs.org/) -- this is to...
**Test small things, with small things** **Test small things, with small things**
### Features ### Features
- Works in the Browser - Designed for the Browser
- Works with CommonJS (aka NodeJS) - *Under* a 100 lines
- Barely over a 100 lines
- Single File - Single File
- No Dependicies - No Dependicies
- 2kb footprint (*before gzip*) - 2kb footprint (*before gzip*)
- Extend with custom reporters - Extend with custom reporters
- Has an Expect-like style BDD assertions - Uses Simple Assert
**No Bloat Here!** **No Bloat Here!**
- [Download Now Available](https://raw.githubusercontent.com/n2geoff/testit/master/src/testit.min.js) - [Download Here](https://raw.githubusercontent.com/n2geoff/testit/master/src/testit.js)
- [Or Minified Version Here](https://raw.githubusercontent.com/n2geoff/testit/master/src/testit.min.js)
## Usage ## Usage
By default, you can run your tests like By default, you can run your tests like
```js ```js
import test from 'testit';
test.it({ test.it({
'my passing test': function() { 'my passing test'() {
test.expects().to.pass(); test.assert(true);
}, },
'my failing test': function() { 'my failing test'() {
test.expects().to.fail('just wanted to fail fast'); test.assert(true === false, 'just wanted to fail fast');
} }
}).run(); }).run();
``` ```
@ -42,18 +44,19 @@ test.it({
by default, your test results are logged to the console by default, your test results are logged to the console
``` ```
+ my passing test +OK my passing test
- my failing test -ERR my failing test
- - Error: just wanted to fail fast ---
Error: just wanted to fail fast
...error stack... ...error stack...
---
# tests 2 pass 1 fail 1 # tests 2 pass 1 fail 1
``` ```
A `+` will proceed test lines that *pass* and a `-` for those that *fail*, the trace back `file:line` is included after the failing test proceeded by `- -` A `+OK` will proceed test lines that *pass* and a `-ERR` for those that *fail*, An error stack is included by default after the failing test wrapped in `---`. You can suppress outputing the error stack by passing `false` as an argument to `run()`, ie `run(false)`.
You can, however, write your own custom test runner... You can, also, write your own custom test runner...
> NOTE: API still in flux, and may change to closer match TAP
### Custom Test Runners ### Custom Test Runners
@ -65,10 +68,10 @@ For Example...
```js ```js
test.it({ test.it({
'my passing test': function() { 'my passing test'() {
test.pass(); test.assert(true);
} }
}, function(results) { }, (results) => {
if (window.document && document.body) { if (window.document && document.body) {
document.body.style.backgroundColor = ( document.body.style.backgroundColor = (
results.fail.length ? '#ff9999' : '#99ff99' results.fail.length ? '#ff9999' : '#99ff99'
@ -88,38 +91,29 @@ If using the optional `next` param will return results as JSON
From this object you can easily find the number of tests ran `pass.length`, number of failed tests `fail.length` or the total test count by adding the two. Simple. From this object you can easily find the number of tests ran `pass.length`, number of failed tests `fail.length` or the total test count by adding the two. Simple.
A sample test runner is provided for both **HTML** and **NODE** in the `test/` directory; `run.html` and `run.js` respectfully. > REMEMBER: you can bypass error output too
A sample test runner is provided for the **BROWSER** in the `test/` directory; `index.html` and `runner.js` respectfully, with the spec in `index.spec.js`.
## Methods ## Methods
To stay minimal, `test.it` only has 3 core functions: To stay minimal, `test.it` only has 3 core functions:
- `it` to capture your tests - `it` to capture your tests
- `run` to execute yours tests - `run` to execute yours tests
- and `expects` to write your test assertions - and `assert` to write your assertions
While you can use your own assertion library, the included `expects` provides the following methods for writing your tests: While you can use your own assertion library, the included `assert` evaluates an expression/condition tests:
| Methods | Description |
| --------------------------------- | --------------------------------------- |
| `.expects(tests).to.exist()` | truthy evalution if value exists |
| `.expects().to.pass()` | pass test |
| `.expects().to.fail(message)` | fails test with message |
| `.expects(this).to.equal(that)` | strictly equal evaluation using `===` |
| `.expects(this).to.be.like(that)` | loose evaluation using `==` |
| `.expects(123).to.be.a('number')` | check typeof value (`.a()` or `.an()`) |
> NOTE: wish `eval` was not so evil, `assert(expression, message)` would be ideal
if you want to shorten test typing try if you want to shorten test typing try
let expect = test.expects; let assert = test.assert;
putting that above your tests will allow you to write like putting that above your tests will allow you to write like
```js ```js
test.it({ test.it({
"my test should work": function() { "my test should work"() {
expect().to.pass(); assert(true);
} }
}); });
@ -127,8 +121,8 @@ test.it({
## TODO ## TODO
- write `not` expects, ie `expects(this).to.not.equal(this)`
- provide sample test runner for CI environments - provide sample test runner for CI environments
- maybe spec files export results && runner identifies failure
## Support ## Support
@ -136,8 +130,8 @@ Please open [an issue](https://github.com/n2geoff/testit/issues/new) for support
## Contributing ## Contributing
Anyone is welcome to contribute, however, if you decide to get involved, please take a moment to review the [guidelines](CONTRIBUTING.md), there minimalistic;) Anyone is welcome to contribute, however, if you decide to get involved, please take a moment to review the [guidelines](CONTRIBUTING.md), they're minimalistic;)
## License ## License
[MIT](LICENSE) [MIT](LICENSE) Geoff Doty

94
dist/testit.js vendored
View File

@ -1,94 +0,0 @@
/*! Test.it v 0.7.0 | MIT | https://github.com/n2geoff/testit */
(function (root, factory) {
"use strict";
if (typeof module === "object" && module.exports) {
module.exports = factory(root.test);
} else {
root.test = factory(root.test);
}
}(this, function () {
"use strict";
const test = {
"_tests": {},
"run": function (next) {
let tests = this._tests;
let failed = [];
let passed = [];
Object.keys(tests).forEach(function (name) {
let test = tests[name];
try {
test();
passed.push(`\n+ ${name}`);
} catch (err) {
failed.push(`\n- ${name}`);
console.error(err);
}
});
if(typeof next === "function") {
return next({
pass: passed,
fail: failed
});
} else {
console.log(...passed, ...failed);
console.log(`\n# tests ${failed.length + passed.length} pass ${passed.length} fail ${failed.length}`);
return failed.length ? false : true;
}
},
"it": function (tests) {
this._tests = tests;
return this;
},
"expects": (val) => {
return {
"to": {
"be": {
"a": (type) => {
return test.expects(val).to.be.an(type);
},
"an": (type) => {
if(['array'].indexOf(type) !== -1) {
if(val.constructor.name.toLowerCase() !== 'array') {
throw new Error(`expected ${typeof val} to be an ${type}`);
}
return true;
}
if(typeof val !== type) {
throw new Error(`expected ${typeof val} to be an ${type}`);
}
},
"like": (comp) => {
if(val != comp) {
throw new Error(`expected ${val} == ${comp}`);
}
}
},
"equal": (comp) => {
if(val !== comp) {
throw new Error(`expected ${val} === ${comp}`);
}
},
"exist": () => {
if(!val) {
throw new Error(`expected ${val} to be truthy`);
}
},
"pass": () => { return true; },
"fail": (msg) => { throw new Error(msg); }
}
};
}
};
return test;
}));

11
dist/testit.min.js vendored
View File

@ -1,2 +1,9 @@
/*! Test.it v 0.7.0 | MIT | https://github.com/n2geoff/testit */ /*! Test.it v1.2.0 | MIT | https://github.com/n2geoff/testit */const o={log:console.log,version:"v1.2.0",_tests:{},run(t,s){typeof t!="boolean"&&(s=t,t=!0);let r=this._tests||[],e=[],l=[];return Object.keys(r).forEach(n=>{let h=r[n];try{h(),l.push(`
!function(t,e){"use strict";"object"==typeof module&&module.exports?module.exports=e(t.test):t.test=e(t.test)}(this,function(){"use strict";const t={_tests:{},run:function(t){let e=this._tests,r=[],o=[];return Object.keys(e).forEach(function(t){let n=e[t];try{n(),o.push(`\n+ ${t}`)}catch(e){r.push(`\n- ${t}`),console.error(e)}}),"function"==typeof t?t({pass:o,fail:r}):(console.log(...o,...r),console.log(`\n# tests ${r.length+o.length} pass ${o.length} fail ${r.length}`),!r.length)},it:function(t){return this._tests=t,this},expects:e=>({to:{be:{a:r=>t.expects(e).to.be.an(r),an:t=>{if(-1!==["array"].indexOf(t)){if("array"!==e.constructor.name.toLowerCase())throw new Error(`expected ${typeof e} to be an ${t}`);return!0}if(typeof e!==t)throw new Error(`expected ${typeof e} to be an ${t}`)},like:t=>{if(e!=t)throw new Error(`expected ${e} == ${t}`)}},equal:t=>{if(e!==t)throw new Error(`expected ${e} === ${t}`)},exist:()=>{if(!e)throw new Error(`expected ${e} to be truthy`)},pass:()=>!0,fail:t=>{throw new Error(t)}}})};return t}); +OK ${n}`)}catch(i){t?e.push(`
-ERR ${n}
---
${i.stack}
---`):e.push(`
-ERR ${n}`)}}),typeof s=="function"?s({pass:l,fail:e}):(o.log(...l,...e),o.log(`
# tests ${e.length+l.length} pass ${l.length} fail ${e.length}`),!e.length)},it(t){return this._tests=t,this},assert(t,s){try{if(!t)throw new Error(s||"Assertion Failed")}catch{throw new Error(s)}}};var f=o;export{f as default,o as test};
//# sourceMappingURL=testit.min.js.map

7
dist/testit.min.js.map vendored Normal file
View File

@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../src/testit.js"],
"sourcesContent": ["/*! Test.it v1.2.0 | MIT | https://github.com/n2geoff/testit */\nexport const test = {\n log: console.log,\n version: \"v1.2.0\",\n _tests: {},\n run(errors, next) {\n // TODO: rewrite to allow show errors flag (optional)\n if(typeof errors !== \"boolean\") {\n next = errors;\n errors = true;\n }\n\n let tests = this._tests || [];\n // capture results\n let failed = [];\n let passed = [];\n\n // loop through tests\n Object.keys(tests).forEach((name) => {\n let test = tests[name];\n\n // execute\n try {\n test();\n passed.push(`\\n+OK ${name}`);\n } catch (err) {\n if (errors) {\n failed.push(`\\n-ERR ${name} \\n --- \\n ${err.stack} \\n ---`);\n } else {\n failed.push(`\\n-ERR ${name}`);\n }\n }\n });\n\n // summary\n if(typeof next === \"function\") {\n return next({\n pass: passed,\n fail: failed\n });\n } else {\n test.log(...passed, ...failed);\n test.log(`\\n# tests ${failed.length + passed.length} pass ${passed.length} fail ${failed.length}`);\n\n return failed.length ? false : true;\n }\n },\n it(tests) {\n this._tests = tests;\n return this;\n },\n assert(expression, msg) {\n try {\n if(!expression) {\n throw new Error(msg || \"Assertion Failed\");\n }\n } catch {\n throw new Error(msg);\n }\n }\n};\n\nexport default test;\n"],
"mappings": "AAAA,+DACO,MAAMA,EAAO,CAChB,IAAK,QAAQ,IACb,QAAS,SACT,OAAQ,CAAC,EACT,IAAIC,EAAQC,EAAM,CAEX,OAAOD,GAAW,YACjBC,EAAOD,EACPA,EAAS,IAGb,IAAIE,EAAQ,KAAK,QAAU,CAAC,EAExBC,EAAS,CAAC,EACVC,EAAS,CAAC,EAoBd,OAjBA,OAAO,KAAKF,CAAK,EAAE,QAASG,GAAS,CACjC,IAAIN,EAAOG,EAAMG,CAAI,EAGrB,GAAI,CACAN,EAAK,EACLK,EAAO,KAAK;AAAA,MAASC,CAAI,EAAE,CAC/B,OAASC,EAAK,CACNN,EACAG,EAAO,KAAK;AAAA,OAAUE,CAAI;AAAA;AAAA,GAAcC,EAAI,KAAK;AAAA,KAAS,EAE1DH,EAAO,KAAK;AAAA,OAAUE,CAAI,EAAE,CAEpC,CACJ,CAAC,EAGE,OAAOJ,GAAS,WACRA,EAAK,CACR,KAAMG,EACN,KAAMD,CACV,CAAC,GAEDJ,EAAK,IAAI,GAAGK,EAAQ,GAAGD,CAAM,EAC7BJ,EAAK,IAAI;AAAA,UAAaI,EAAO,OAASC,EAAO,MAAM,SAASA,EAAO,MAAM,SAASD,EAAO,MAAM,EAAE,EAE1F,CAAAA,EAAO,OAEtB,EACA,GAAGD,EAAO,CACN,YAAK,OAASA,EACP,IACX,EACA,OAAOK,EAAYC,EAAK,CACpB,GAAI,CACA,GAAG,CAACD,EACA,MAAM,IAAI,MAAMC,GAAO,kBAAkB,CAEjD,MAAQ,CACJ,MAAM,IAAI,MAAMA,CAAG,CACvB,CACJ,CACJ,EAEA,IAAOC,EAAQV",
"names": ["test", "errors", "next", "tests", "failed", "passed", "name", "err", "expression", "msg", "testit_default"]
}

26
eslint.config.mjs Normal file
View File

@ -0,0 +1,26 @@
import globals from "globals";
import path from "node:path";
import { fileURLToPath } from "node:url";
import js from "@eslint/js";
import { FlatCompat } from "@eslint/eslintrc";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname,
recommendedConfig: js.configs.recommended,
allConfig: js.configs.all
});
export default [...compat.extends("eslint:recommended"), {
languageOptions: {
globals: {
...globals.browser,
},
ecmaVersion: "latest",
sourceType: "module",
},
rules: {},
}];

View File

@ -1,10 +0,0 @@
const gulp = require("gulp");
const minify = require("gulp-minify");
const strip = require("gulp-strip-comments");
gulp.task("default", function build() {
return gulp.src("./src/testit.js")
.pipe(strip({safe: true}))
.pipe(minify({ext: {min: ".min.js"}}))
.pipe(gulp.dest("dist"))
});

5526
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,21 +1,20 @@
{ {
"name": "testit", "name": "testit.run",
"version": "0.7.0", "version": "1.2.0",
"description": "a minimalistic testing library", "description": "minimalistic client-side testing library",
"main": "src/testit.js", "main": "src/testit.js",
"type": "module",
"directories": { "directories": {
"test": "test" "test": "test"
}, },
"devDependencies": {
"gulp": "^4.0.0",
"gulp-minify": "^3.1.0",
"gulp-strip-comments": "^2.5.2",
"jshint": "^2.9.6"
},
"scripts": { "scripts": {
"build": "node_modules/.bin/gulp", "build": "npx esbuild src/testit.js --minify --sourcemap --format=esm --outfile=dist/testit.min.js",
"lint": "node_modules/.bin/jshint src/testit.js", "lint": "npx eslint src/testit.js",
"test": "node test/run.js" "test": "npx live-server --open=test/ --port=5000"
},
"dependencies": {},
"devDependencies": {
"eslint": "^9.23.0"
}, },
"repository": { "repository": {
"type": "git", "type": "git",

View File

@ -1,35 +1,34 @@
/*! Test.it v 0.6.2 | MIT | https://github.com/n2geoff/testit */ /*! Test.it v1.2.0 | MIT | https://github.com/n2geoff/testit */
(function (root, factory) { export const test = {
"use strict"; log: console.log,
// support browser & commonjs version: "v1.2.0",
if (typeof module === "object" && module.exports) { _tests: {},
module.exports = factory(root.test); run(errors, next) {
} else { // TODO: rewrite to allow show errors flag (optional)
root.test = factory(root.test); if(typeof errors !== "boolean") {
next = errors;
errors = true;
} }
}(this, function () {
"use strict";
const test = { let tests = this._tests || [];
"_tests": {},
"run": function (next) {
let tests = this._tests;
// capture results // capture results
let failed = []; let failed = [];
let passed = []; let passed = [];
// loop through tests // loop through tests
Object.keys(tests).forEach(function (name) { Object.keys(tests).forEach((name) => {
let test = tests[name]; let test = tests[name];
// execute // execute
try { try {
test(); test();
passed.push(`\n+ ${name}`); passed.push(`\n+OK ${name}`);
} catch (err) { } catch (err) {
failed.push(`\n- ${name}`); if (errors) {
console.error(err); failed.push(`\n-ERR ${name} \n --- \n ${err.stack} \n ---`);
} else {
failed.push(`\n-ERR ${name}`);
}
} }
}); });
@ -40,60 +39,25 @@
fail: failed fail: failed
}); });
} else { } else {
console.log(...passed, ...failed); test.log(...passed, ...failed);
console.log(`\n# tests ${failed.length + passed.length} pass ${passed.length} fail ${failed.length}`); test.log(`\n# tests ${failed.length + passed.length} pass ${passed.length} fail ${failed.length}`);
return failed.length ? false : true; return failed.length ? false : true;
} }
}, },
"it": function (tests) { it(tests) {
this._tests = tests; this._tests = tests;
return this; return this;
}, },
"expects": (val) => { assert(expression, msg) {
return { try {
"to": { if(!expression) {
"be": { throw new Error(msg || "Assertion Failed");
"a": (type) => {
return test.expects(val).to.be.an(type);
},
"an": (type) => {
if(['array'].indexOf(type) !== -1) {
if(val.constructor.name.toLowerCase() !== 'array') {
throw new Error(`expected ${typeof val} to be an ${type}`);
} }
} catch {
return true; throw new Error(msg);
} }
if(typeof val !== type) {
throw new Error(`expected ${typeof val} to be an ${type}`);
}
},
"like": (comp) => {
if(val != comp) {
throw new Error(`expected ${val} == ${comp}`);
}
}
},
"equal": (comp) => {
if(val !== comp) {
throw new Error(`expected ${val} === ${comp}`);
}
},
"exist": () => {
if(!val) {
throw new Error(`expected ${val} to be truthy`);
}
},
"pass": () => { return true; },
"fail": (msg) => { throw new Error(msg); }
}
};
} }
}; };
return test; export default test;
}));

17
test/index.html Normal file
View File

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Test It Spec</title>
<style>
#summary {font-size: 2rem; text-transform: uppercase;}
</style>
</head>
<body>
<div id="summary"></div>
<div id="errors"></div>
<script type="module" src="./runner.js"></script>
</body>
</html>

View File

@ -1,33 +1,36 @@
var test = test || require("../src/testit"); import test from "../src/testit.js";
test.it({ export default test.it({
"'like' should do truthy evaluation via ==": function() { "'like' should do truthy evaluation via =="() {
test.expects(1).to.be.like('1'); test.assert(1 == "1");
test.expects("1").to.be.like(1); test.assert(1);
}, },
"'equal' should do === evaluation exist": function() { "'equal' should do === evaluation exist"() {
test.expects(1).to.equal(1); test.assert(1 === 1);
test.expects('hello').to.equal('hello'); test.assert("hello" === "hello");
}, },
"you should be able to 'pass' a test": function() { "you should be able to 'pass' a test"() {
test.expects().to.pass(); test.assert(1);
}, },
"you should be able to fail' a test too": function() { "you should be able to fail' a test too"() {
try { try {
test.expects().to.fail(); test.assert(0);
} catch (e) { } catch (e) {
test.expects().to.pass(); // correct
} }
}, },
"you should be able to see if something 'exists'": function() { "you should be able to test if something 'exists'"() {
test.expects({}).to.exist(); test.assert({});
test.assert(typeof ({}) === "object");
}, },
"should be able to check types": function() { "should be able to check types"() {
test.expects(123).to.be.a('number');
test.expects([]).to.be.an('array'); test.assert(Array.isArray([]));
test.expects({}).to.be.a('object'); test.assert(typeof (123) === "number");
test.expects(true).to.be.a('boolean');
test.expects(false).to.be.a('boolean'); test.assert(typeof ({}) === "object");
test.expects(undefined).to.be.a('undefined'); test.assert(typeof (true) === "boolean");
test.assert(typeof (false) === "boolean");
test.assert(typeof (undefined) === "undefined");
} }
}); });

View File

@ -1,25 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Test It Spec</title>
<script src="../src/testit.js"></script>
<script src="./index.spec.js"></script>
</head>
<body>
<script>
test.run(function(r) {
document.body.style.backgroundColor = (
r.fail.length ? "#ff9999" : "#99ff99"
);
r.pass.forEach((p) => document.write(`<br>${p}`));
r.fail.forEach((f) => document.write(`<br><b>${f}</b>`));
document.write(`<p>tests ${r.pass.length + r.fail.length} pass ${r.pass.length} fail ${r.fail.length}`);
});
</script>
</body>
</html>

View File

@ -1,24 +0,0 @@
var path = require("path");
var fs = require("fs");
fs.readdir(__dirname, function(err, files) {
if(err) {
process.exit(1);
}
var tests = files.filter(function(item) {
return item.indexOf("spec.js") !== -1;
});
tests.forEach(function(file) {
console.log(`: ${file}`);
var me = fs.readFileSync(path.join(__dirname, file))
// eval maybe evil, but its your code, are you evil?
eval(me.toString());
test.run();
});
});

15
test/runner.js Normal file
View File

@ -0,0 +1,15 @@
import spec from "./index.spec.js";
spec.run(false, (r) => {
let errors = [];
document.body.style.backgroundColor = (
r.fail.length ? "#ff9999" : "#99ff99"
);
r.pass.forEach((p) => errors.push(`<br>${p}`));
r.fail.forEach((f) => errors.push(`<br><b>${f}</b>`));
document.querySelector("#errors").innerHTML = errors;
document.querySelector("#summary").innerHTML = `| tests: ${r.pass.length + r.fail.length} | pass: ${r.pass.length} | fail: ${r.fail.length} |`;
});