{"id":16328468,"url":"https://github.com/MithrilJS/ospec","last_synced_at":"2025-10-25T21:30:18.494Z","repository":{"id":40001432,"uuid":"215168648","full_name":"MithrilJS/ospec","owner":"MithrilJS","description":"Noiseless testing framework","archived":false,"fork":false,"pushed_at":"2023-09-17T07:44:59.000Z","size":474,"stargazers_count":50,"open_issues_count":20,"forks_count":13,"subscribers_count":6,"default_branch":"main","last_synced_at":"2024-04-24T16:09:37.856Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/MithrilJS.png","metadata":{"files":{"readme":"README v5 preview.md","changelog":"changelog.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":null,"support":null,"governance":null,"roadmap":null,"authors":null},"funding":{"open_collective":"mithriljs"}},"created_at":"2019-10-15T00:16:01.000Z","updated_at":"2023-11-24T19:57:17.000Z","dependencies_parsed_at":"2024-01-23T21:17:38.965Z","dependency_job_id":"bba747c8-15e9-4feb-8614-cfbebc1934dc","html_url":"https://github.com/MithrilJS/ospec","commit_stats":null,"previous_names":[],"tags_count":8,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MithrilJS%2Fospec","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MithrilJS%2Fospec/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MithrilJS%2Fospec/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MithrilJS%2Fospec/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/MithrilJS","download_url":"https://codeload.github.com/MithrilJS/ospec/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":238207673,"owners_count":19434095,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-10-10T23:14:20.553Z","updated_at":"2025-10-25T21:30:17.682Z","avatar_url":"https://github.com/MithrilJS.png","language":"JavaScript","readme":"# ospec\n\n[![npm License](https://img.shields.io/npm/l/ospec.svg)](https://www.npmjs.com/package/ospec) [![npm Version](https://img.shields.io/npm/v/ospec.svg)](https://www.npmjs.com/package/ospec) ![Build Status](https://img.shields.io/github/actions/workflow/status/MithrilJS/ospec/.github%2Fworkflows%2Fci.yml) [![npm Downloads](https://img.shields.io/npm/dm/ospec.svg)](https://www.npmjs.com/package/ospec)\n\n[![Donate at OpenCollective](https://img.shields.io/opencollective/all/mithriljs.svg?colorB=brightgreen)](https://opencollective.com/mithriljs) [![Zulip, join chat](https://img.shields.io/badge/zulip-join_chat-brightgreen.svg)](https://mithril.zulipchat.com/)\n\n---\n\n[About](#about) | [Usage](#usage) | [CLI](#command-line-interface) | [API](#api) | [Goals](#goals)\n\nNoiseless testing framework\n\n## About\n\n- ~660 LOC including the CLI runner\n- terser and faster test code than with mocha, jasmine or tape\n- test code reads like bullet points\n- assertion code follows [SVO](https://en.wikipedia.org/wiki/Subject–verb–object) structure in present tense for terseness and readability\n- supports:\n  - test grouping\n  - assertions\n  - spies\n  - `equals`, `notEquals`, `deepEquals` and `notDeepEquals` assertion types\n  - `before`/`after`/`beforeEach`/`afterEach` hooks\n  - test exclusivity (i.e. `.only`)\n  - async tests and hooks\n- explicitly regulates test-space configuration to encourage focus on testing, and to provide uniform test suites across projects\n\n## Usage\n\n### Single tests\n\nBoth tests and assertions are declared via the `o` function. Tests should have a description and a body function. A test may have one or more assertions. Assertions should appear inside a test's body function and compare two values.\n\n```javascript\nvar o = require(\"ospec\")\n\no(\"addition\", o =\u003e {\n    o(1 + 1).equals(2)\n})\no(\"subtraction\", o =\u003e {\n    o(1 - 1).notEquals(2)\n})\n```\n\nAssertions may have descriptions:\n\n```javascript\no(\"addition\", o =\u003e {\n    o(1 + 1).equals(2)(\"addition should work\")\n\n    /* in ES6, the following syntax is also possible\n    o(1 + 1).equals(2) `addition should work`\n    */\n})\n/* for a failing test, an assertion with a description outputs this:\n\naddition should work\n\n1 should equal 2\n\nError\n  at stacktrace/goes/here.js:1:1\n*/\n```\n\n### Grouping tests\n\nTests may be organized into logical groups using `o.spec`\n\n```javascript\no.spec(\"math\", () =\u003e {\n    o(\"addition\", o =\u003e {\n        o(1 + 1).equals(2)\n    })\n    o(\"subtraction\", o =\u003e {\n        o(1 - 1).notEquals(2)\n    })\n})\n```\n\nGroup names appear as a breadcrumb trail in test descriptions: `math \u003e addition: 2 should equal 2`\n\n### Nested test groups\n\nGroups can be nested to further organize test groups. Note that tests cannot be nested inside other tests.\n\n```javascript\no.spec(\"math\", () =\u003e {\n    o.spec(\"arithmetics\", () =\u003e {\n        o(\"addition\", o =\u003e {\n            o(1 + 1).equals(2)\n        })\n        o(\"subtraction\", o =\u003e {\n            o(1 - 1).notEquals(2)\n        })\n    })\n})\n```\n\n### Callback test\n\nThe `o.spy()` method can be used to create a stub function that keeps track of its call count and received parameters\n\n```javascript\n//code to be tested\nfunction call(cb, arg) {cb(arg)}\n\n//test suite\nvar o = require(\"ospec\")\n\no.spec(\"call()\", () =\u003e {\n    o(\"works\", o =\u003e {\n        var spy = o.spy()\n        call(spy, 1)\n\n        o(spy.callCount).equals(1)\n        o(spy.args[0]).equals(1)\n        o(spy.calls[0]).deepEquals([1])\n    })\n})\n```\n\nA spy can also wrap other functions, like a decorator:\n\n```javascript\n//code to be tested\nvar count = 0\nfunction inc() {\n    count++\n}\n\n//test suite\nvar o = require(\"ospec\")\n\no.spec(\"call()\", () =\u003e {\n    o(\"works\", o =\u003e {\n        var spy = o.spy(inc)\n        spy()\n\n        o(count).equals(spy.callCount)\n    })\n})\n\n```\n\n### Asynchronous tests\n\n```javascript\no(\"setTimeout calls callback\", o =\u003e {\n    return new Promise(fulfill =\u003e setTimeout(fulfill, 10))\n})\n```\n\nAlternativly you can return a promise or even use an async function in tests:\n\n```javascript\no(\"promise test\", o =\u003e {\n    return new Promise(resolve =\u003e {\n        setTimeout(resolve, 10)\n    })\n})\n```\n\n```javascript\no(\"promise test\", async () =\u003e {\n    await someOtherAsyncFunction()\n})\n```\n\n#### Timeout delays\n\nBy default, asynchronous tests time out after 200ms. You can change that default for the current test suite and\nits children by using the `o.specTimeout(delay)` function.\n\n```javascript\no.spec(\"a spec that must timeout quickly\", () =\u003e {\n    // wait 20ms before bailing out of the tests of this suite and\n    // its descendants\n    const waitFor = n =\u003e new Promise(f =\u003e setTimeout(f, n))\n    o.specTimeout(20)\n    o(\"some test\", async o =\u003e {\n        await waitFor(10)\n        o(1 + 1).equals(2)\n    })\n\n    o.spec(\"a child suite where the delay also applies\", () =\u003e {\n        o(\"some test\", async o =\u003e {\n            await waitFor(30) // this will cause a timeout to be reported\n            o(1 + 1).equals(2)// even if the assertions succeed.\n        })\n    })\n})\no.spec(\"a spec that uses the default delay\", () =\u003e {\n    // ...\n})\n```\n\nThis can also be changed on a per-test basis using the `o.timeout(delay)` function from within a test:\n\n```javascript\nconst waitFor = n =\u003e new Promise(f =\u003e setTimeout(f, n))\no(\"setTimeout calls callback\", async o =\u003e {\n    o.timeout(500) //wait 500ms before setting the test as timed out and moving forward.\n    await(300)\n    o(1 + 1).equals(2)\n})\n```\n\nNote that the `o.timeout` function call must be the first statement in its test.\n\nTest timeouts are reported along with test failures and errors thrown at the end of the run. A test timeout causes the test runner to exit with a non-zero status code.\n\n### `before`, `after`, `beforeEach`, `afterEach` hooks\n\nThese hooks can be declared when it's necessary to setup and clean up state for a test or group of tests. The `before` and `after` hooks run once each per test group, whereas the `beforeEach` and `afterEach` hooks run for every test.\n\n```javascript\no.spec(\"math\", () =\u003e {\n    var acc\n    o.beforeEach(() =\u003e {\n        acc = 0\n    })\n\n    o(\"addition\", o =\u003e {\n        acc += 1\n\n        o(acc).equals(1)\n    })\n    o(\"subtraction\", o =\u003e {\n        acc -= 1\n\n        o(acc).equals(-1)\n    })\n})\n```\n\nIt's strongly recommended to ensure that `beforeEach` hooks always overwrite all shared variables, and avoid `if/else` logic, memoization, undo routines inside `beforeEach` hooks.\n\nYou can run assertions from the hooks:\n\n```javascript\no.afterEach(o =\u003e {\n    o(postConditions).equals(met)\n})\n```\n\n### Asynchronous hooks\n\nLike tests, hooks can also be asynchronous. Tests that are affected by asynchronous hooks will wait for the hooks to complete before running.\n\n```javascript\no.spec(\"math\", () =\u003e {\n    let state\n    o.beforeEach(async() =\u003e {\n        // async initialization\n        state = await (async function () {return 0})()\n    })\n\n    //tests only run after the async hooks are complete\n    o(\"addition\", o =\u003e {\n        state += 1\n\n        o(state).equals(1)\n    })\n    o(\"subtraction\", o =\u003e {\n        acc -= 1\n\n        o(state).equals(-1)\n    })\n})\n```\n\nTo ease the transition from older `ospec` versions to the v5+ API, we also provide a `done` helper, to be used as follow:\n\n```javascript\no(\"setTimeout calls callback\", ({o, done}) =\u003e {\n    setTimeout(()=\u003e{\n        if (error) done(error)\n        else done()\n    }), 10)\n})\n```\n\nIf an argument is passed to `done`, the corresponding promise is rejected.\n\n### Running only some tests\n\nOne or more tests can be temporarily made to run exclusively by calling `o.only()` instead of `o`. This is useful when troubleshooting regressions, to zero-in on a failing test, and to avoid saturating console log w/ irrelevant debug information.\n\n```javascript\no.spec(\"math\", () =\u003e {\n    // will not run\n    o(\"addition\", o =\u003e {\n        o(1 + 1).equals(2)\n    })\n\n    // this test will be run, regardless of how many groups there are\n    o.only(\"subtraction\", () =\u003e {\n        o(1 - 1).notEquals(2)\n    })\n\n    // will not run\n    o(\"multiplication\", o =\u003e {\n        o(2 * 2).equals(4)\n    })\n\n    // this test will be run, regardless of how many groups there are\n    o.only(\"division\", () =\u003e {\n        o(6 / 2).notEquals(2)\n    })\n})\n```\n\n### Running the test suite\n\n```javascript\n//define a test\no(\"addition\", o =\u003e {\n    o(1 + 1).equals(2)\n})\n\n//run the suite\no.run()\n```\n\n### Running test suites concurrently\n\nThe `o.new()` method can be used to create new instances of ospec, which can be run in parallel. Note that each instance will report independently, and there's no aggregation of results.\n\n```javascript\nvar _o = o.new('optional name')\n_o(\"a test\", o =\u003e {\n    o(1).equals(1)\n})\n_o.run()\n```\n\n## Command Line Interface\n\nCreate a script in your package.json:\n\n```javascript\n    \"scripts\": {\n        \"test\": \"ospec\",\n        ...\n    }\n```\n\n...and run it from the command line:\n\n```shell\nnpm test\n```\n\n**NOTE:** `o.run()` is automatically called by the CLI runner - no need to call it in your test code.\n\n### CLI Options\n\nRunning ospec without arguments is equivalent to running `ospec '**/tests/**/*.js'`. In english, this tells ospec to evaluate all `*.js` files in any sub-folder named `tests/` (the `node_modules` folder is always excluded).\n\nIf you wish to change this behavior, just provide one or more glob match patterns:\n\n```shell\nospec '**/spec/**/*.js' '**/*.spec.js'\n```\n\nYou can also provide ignore patterns (note: always add `--ignore` AFTER match patterns):\n\n```shell\nospec --ignore 'folder1/**' 'folder2/**'\n```\n\nFinally, you may choose to load files or modules before any tests run (**note:** always add `--preload` AFTER match patterns):\n\n```shell\nospec --preload esm\n```\n\nHere's an example of mixing them all together:\n\n```shell\nospec '**/*.test.js' --ignore 'folder1/**' --preload esm ./my-file.js\n```\n\n### native mjs and module support\n\nFor Node.js versions \u003e= 13.2, `ospec` supports both ES6 modules and CommonJS packages out of the box. `--preload esm` is thus not needed in that case.\n\n### Run ospec directly from the command line\n\nospec comes with an executable named `ospec`. npm auto-installs local binaries to `./node_modules/.bin/`. You can run ospec by running `./node_modules/.bin/ospec` from your project root, but there are more convenient methods to do so that we will soon describe.\n\nospec doesn't work when installed globally (`npm install -g`). Using global scripts is generally a bad idea since you can end up with different, incompatible versions of the same package installed locally and globally.\n\nHere are different ways of running ospec from the command line. This knowledge applies to not just ospec, but any locally installed npm binary.\n\n#### npx\n\nIf you're using a recent version of npm (v5+), you can use run `npx ospec` from your project folder.\n\n#### npm-run\n\nIf you're using a recent version of npm (v5+), you can use run `npx ospec` from your project folder.\n\nOtherwise, to work around this limitation, you can use [`npm-run`](https://www.npmjs.com/package/npm-run) which enables one to run the binaries of locally installed packages.\n\n```shell\nnpm install npm-run -g\n```\n\nThen, from a project that has ospec installed as a (dev) dependency:\n\n```shell\nnpm-run ospec\n```\n\n#### PATH\n\nIf you understand how your system's PATH works (e.g. for [OSX](https://coolestguidesontheplanet.com/add-shell-path-osx/)), then you can add the following to your PATH...\n\n```shell\nexport PATH=./node_modules/.bin:$PATH\n```\n\n...and you'll be able to run `ospec` without npx, npm, etc. This one-time setup will also work with other binaries across all your node projects, as long as you run binaries from the root of your projects.\n\n---\n\n## API\n\nSquare brackets denote optional arguments\n\n### `o.spec(title: string, tests: () =\u003e void) =\u003e void`\n\nDefines a group of tests. Groups are optional\n\n---\n\n### `o(title: string,  assertions: (o: AssertionFactory) =\u003e void) =\u003e void`\n\nDefines a test. The `assertions` function can be async. It receives the assertion factory as argument.\n\n---\n\n### `type AssertionFactory = (value: any) =\u003e Assertion`\n\nStarts an assertion. There are seven types of assertion: `equals`, `notEquals`, `deepEquals`, `notDeepEquals`, `throws`, `notThrows`, and, for extensions, `_`.\n\n```typescript\ntype OptionalMessage = (message:string) =\u003e void\n\ntype AssertionResult = {pass: boolean, message: string}\n\ninterface Assertion {\n  equals: (value: any) =\u003e OptionalMessage\n  notEquals: (value: any) =\u003e OptionalMessage\n  deepEquals: (value: any) =\u003e OptionalMessage\n  notDeepEquals: (value: any) =\u003e OptionalMessage\n  throws: (value: any) =\u003e OptionalMessage\n  notThrows: (value: any) =\u003e OptionalMessage\n  // For plugins:\n  _: (validator: ()=\u003eAssertionResult) =\u003e void\n}\n\n```\n\nAssertions have this form:\n\n```javascript\no(actualValue).equals(expectedValue)\n```\n\nAs a matter of convention, the actual value should be the first argument and the expected value should be the second argument in an assertion.\n\nAssertions can also accept an optional description curried parameter:\n\n```javascript\no(actualValue).equals(expectedValue)(\"this is a description for this assertion\")\n```\n\nAssertion descriptions can be simplified using ES6 tagged template string syntax:\n\n```javascript\no(actualValue).equals(expectedValue)`likewise, with an interpolated ${value}`\n```\n\n#### `o(value: any).equals(value: any)`\n\nAsserts that two values are strictly equal (`===`). Returns an `OptionalMessage` that can be called if desired to contextualize the assertion message.\n\n#### `o(value: any).notEquals(value: any)`\n\nAsserts that two values are strictly not equal (`!==`). Returns an `OptionalMessage` that can be called if desired to contextualize the assertion message.\n\n#### `o(value: any).deepEquals(value: any)`\n\nAsserts that two values are recursively equal. Returns an `OptionalMessage` that can be called if desired to contextualize the assertion message.\n\n#### `o(value: any).notDeepEquals(value: any)`\n\nAsserts that two values are not recursively equal. Returns an `OptionalMessage` that can be called if desired to contextualize the assertion message.\n\n#### `o(fn: (...args: any[]) =\u003e any).throws(fn: constructor)`\n\nAsserts that a function throws an instance of the provided constructor. Returns an `OptionalMessage` that can be called if desired to contextualize the assertion message.\n\n#### `o(fn: (...args: any[]) =\u003e any).throws(message: string)`\n\nAsserts that a function throws an Error with the provided message. Returns an `OptionalMessage` that can be called if desired to contextualize the assertion message.\n\n#### `o(fn: (...args: any[]) =\u003e any).notThrows(fn: constructor)`\n\nAsserts that a function does not throw an instance of the provided constructor. Returns an `OptionalMessage` that can be called if desired to contextualize the assertion message.\n\n#### `o(fn: (...args: any[]) =\u003e any).notThrows(message: string)`\n\nAsserts that a function does not throw an Error with the provided message. Returns an `OptionalMessage` that can be called if desired to contextualize the assertion message.\n\n---\n\n### `o.before(setup: (o: AssertionFactoy) =\u003e void)`\n\nDefines code to be run at the beginning of a test group.\n\nThe `AssertionFactory` is injected as an argument into the `setup` function. It is called `o` by convention.\n\n---\n\n### `o.after(teardown: (o: AssertionFactoy) =\u003e void)`\n\nDefines code to be run at the end of a test group.\n\nThe `AssertionFactory` is injected as an argument into the `setup` function. It is called `o` by convention.\n\n---\n\n### `o.beforeEach(setup: (o: AssertionFactoy) =\u003e void)`\n\nDefines code to be run before each test in a group.\n\nThe `AssertionFactory` is injected as an argument into the `setup` function. It is called `o` by convention.\n\n---\n\n### `o.after(teardown: (o: AssertionFactoy) =\u003e void)`\n\nDefines code to be run after each test in a group.\n\nThe `AssertionFactory` is injected as an argument into the `setup` function. It is called `o` by convention.\n\n---\n\n### `o.only(title: string, assertions: (o: AssertionFactoy) =\u003e void)`\n\nYou can replace a `o(\"message\", o=\u003e{/* assertions */})` call with `o.only(\"message\", o=\u003e{/* assertions */})`. If `o.only` is encountered plain `o()` test definitions will be ignored, and those maked as `only` will be the only ones to run.\n\n---\n\n### `o.spy(fn: (...args: any[]) =\u003e any)`\n\nReturns a function that records the number of times it gets called, and its arguments.\n\nThe resulting function has the same `.name` and `.length` properties as the one `o.spy()` received as argument. It also has the following additional properties:\n\n#### `o.spy().callCount`\n\nThe number of times the function has been called\n\n#### `o.spy().args`\n\nThe `arguments` that were passed to the function in the last time it was called\n\n#### `o.spy().calls`\n\nAn array of `{this, args}` objects that reflect, for each time the spied on function was called, the `this` value recieved if it was called as a method, and the corresponding `args`.\n\n---\n\n### `o.run(reporter: (results: Result[]) =\u003e number)`\n\nRuns the test suite. By default passing test results are printed using\n`console.log` and failing test results are printed using `console.error`.\n\nIf you have custom continuous integration needs then you can use a\nreporter to process [test result data](#result-data) yourself.\n\nIf running in Node.js, ospec will call `process.exit` after reporting\nresults by default. If you specify a reporter, ospec will not do this\nand allows your reporter to respond to results in its own way.\n\n---\n\n### `o.report(results: Result[])`\n\nThe default reporter used by `o.run()` when none are provided. Returns the number of failures. It expects an array of [test result data](#result-data) as argument.\n\n---\n\n### `o.new()`\n\nReturns a new instance of ospec. Useful if you want to run more than one test suite concurrently\n\n```javascript\nvar $o = o.new()\n$o(\"a test\", o =\u003e {\n    o(1).equals(1)\n})\n$o.run()\n```\n\n### throwing Errors\n\nWhen an error is thrown some tests may be skipped. See the \"run time model\" for a detailed description of the bailout mechanism.\n\n---\n\n## Result data\n\nTest results are available by reference for integration purposes. You\ncan use custom reporters in `o.run()` to process these results.\n\n```javascript\ninterface Result {\n    pass: Boolean | null,\n    message: string,\n    context: string,\n    error: Error,\n    testError: Error,\n}\n\no.run((results: Results[]) =\u003e {\n    // results is an array\n\n    results.forEach(result =\u003e {\n        // ...\n    })\n})\n```\n\n---\n\n### `result.pass`\n\n- `true` if the assertion passed.\n- `false` if the assertion failed.\n- `null` if the assertion was incomplete (`o(\"partial assertion\")` without an assertion method called).\n\n---\n\n### `result.error`\n\nThe `Error` object explaining the reason behind a failure. If the assertion failed, the stack will point to the actuall error. If the assertion did pass or was incomplete, this field is identical to `result.testError`.\n\n---\n\n### `result.testError`\n\nAn `Error` object whose stack points to the test definition that wraps the assertion. Useful as a fallback because in some async cases the main may not point to test code.\n\n---\n\n### `result.message`\n\nIf an exception was thrown inside the corresponding test, this will equal that Error's `message`. Otherwise, this will be a preformatted message in [SVO form](https://en.wikipedia.org/wiki/Subject%E2%80%93verb%E2%80%93object). More specifically, `${subject}\\n${verb}\\n${object}`.\n\nAs an example, the following test's result message will be `\"false\\nshould equal\\ntrue\"`.\n\n```javascript\no.spec(\"message\", () =\u003e {\n    o(false).equals(true)\n})\n```\n\nIf you specify an assertion description, that description will appear two lines above the subject.\n\n```javascript\no.spec(\"message\", () =\u003e {\n    o(false).equals(true)(\"Candyland\") // result.message === \"Candyland\\n\\nfalse\\nshould equal\\ntrue\"\n})\n```\n\n---\n\n### `result.context`\n\nA `\u003e`-separated string showing the structure of the test specification.\nIn the below example, `result.context` would be `testing \u003e rocks`.\n\n```javascript\no.spec(\"testing\", () =\u003e {\n    o.spec(\"rocks\", () =\u003e {\n        o(false).equals(true)\n    })\n})\n```\n\n---\n\n## Run time model\n\n### Definitions\n\n- A **test** is the function passed to `o(\"description\", function test() {})`.\n- A **hook** is a function passed to `o.before()`, `o.after()`. `o.beforeEach()` and `o.afterEach()`.\n- A **task** designates either a test or a hook.\n- A given test and its associated `beforeEach` and `afterEach` hooks form a **streak**. The `beforeEach` hooks run outermost first, the `afterEach` run outermost last. The hooks are optional, and are tied at test-definition time in the `o.spec()` calls that enclose the test.\n- A **spec** is a collection of streaks, specs, one `before` hook and one `after` hook. Each component is optional. Specs are defined with the `o.spec(\"spec name\", function specDef() {})` calls.\n\n### The phases of an ospec run\n\nFor a given instance, an `ospec` run goes through three phases:\n\n1) tests definition\n1) tests execution and results accumulation\n1) results presentation\n\n#### Tests definition\n\nThis phase is synchronous. `o.spec(\"spec name\", function specDef() {})`, `o(\"test name\", function test() {})` and hooks calls generate a tree of specs and tests.\n\n#### Test execution and results accumulation\n\nAt test execution time, for each spec, the `before` hook is called if present, then nested specs the streak of each test, in definition order, then the `after` hook, if present.\n\nTest and hooks may contain assertions, which will populate the `results` array.\n\n#### Results presentation\n\nOnce all tests have run or timed out, the results are presented.\n\n### Throwing errors and spec bail out\n\nWhile some testing libraries consider error thrown as assertions failure, `ospec` treats them as super-failures. Throwing will cause the current spec to be aborted, avoiding what can otherwise end up as pages of errors. What this means depends on when the error is thrown. Specifically:\n\n- A syntax error in a file causes the file to be ignored by the runner.\n- At test-definition time:\n  - An error thrown at the root of a file will cause subsequent tests and specs to be ignored.\n  - An error thrown in a spec definition will cause the spec to be ignored.\n- At test-execution time:\n  - An error thrown in the `before` hook will cause the streaks and nested specs to be ignored. The `after` hook will run.\n  - An error thrown in a task...\n    - ...prevents further streaks and nested specs in the current spec from running. The `after` *hook* of the spec will run.\n    - ...if thrown in a `beforeEach` hook of a streak, causes the streak to be hollowed out. Hooks defined in nested scopes and the actual test will not run. However, the `afterEach` hook corresponding to the one that crashed will run, as will those defined in outer scopes.\n\nFor every error thrown, a \"bail out\" failure is reported.\n\n---\n\n## Goals\n\nOspec started as a bare bones test runner optimized for Leo Horie to write Mithril v1 with as little hasle as possible. It has since grown in capabilities and polish, and while we tried to keep some of the original spirit, the current incarnation is not as radically minimalist as the original. The state of the art in testing has also moved with the dominance of Jest over Jasmine and Mocha, and now Vitest coming up the horizon. The goals in 2023 are:\n\n- Do the most common things that the mocha/chai/sinon triad does without having to install 3 different libraries and several dozen dependencies\n- Limit configuration in test-space:\n  - Disallow ability to pick between API styles (BDD/TDD/Qunit, assert/should/expect, etc)\n  - No \"magic\" plugin system with global reach.\n  - Provide a default simple reporter\n- Make assertion code terse, readable and self-descriptive\n- Have as few assertion types as possible for a workable usage pattern\n- Don't flood the result log with failures if you break a core part of the project you're testing. An error thrown in test space will abort the current spec.\n\nThese restrictions have a few benefits:\n\n- tests always look the same, even across different projects and teams\n- single source of documentation for entire testing API\n- no need to hunt down plugins to figure out what they do, especially if they replace common javascript idioms with fuzzy spoken language constructs (e.g. what does `.is()` do?)\n- no need to pollute project-space with ad-hoc configuration code\n- discourages side-tracking and yak-shaving\n","funding_links":["https://opencollective.com/mithriljs"],"categories":["JavaScript"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FMithrilJS%2Fospec","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FMithrilJS%2Fospec","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FMithrilJS%2Fospec/lists"}