{"id":15017388,"url":"https://github.com/pubkey/async-test-util","last_synced_at":"2025-04-11T01:01:38.149Z","repository":{"id":22678810,"uuid":"96754937","full_name":"pubkey/async-test-util","owner":"pubkey","description":"Utility functions that are useful in async/await tests :thumbsup:","archived":false,"fork":false,"pushed_at":"2025-04-10T07:53:56.000Z","size":209,"stargazers_count":27,"open_issues_count":0,"forks_count":2,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-04-10T08:43:26.863Z","etag":null,"topics":["assert","async","async-await","jasmine","javascript","karma","mocha","testcafe","testing"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/pubkey.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-07-10T08:35:31.000Z","updated_at":"2025-04-10T07:53:59.000Z","dependencies_parsed_at":"2023-02-14T15:31:32.630Z","dependency_job_id":"2fa92de9-4ebd-4f26-a29c-bd42cdb12165","html_url":"https://github.com/pubkey/async-test-util","commit_stats":{"total_commits":219,"total_committers":5,"mean_commits":43.8,"dds":0.730593607305936,"last_synced_commit":"934df05063610fb9b8fd3e7515bcd1cb9c00899b"},"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pubkey%2Fasync-test-util","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pubkey%2Fasync-test-util/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pubkey%2Fasync-test-util/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pubkey%2Fasync-test-util/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/pubkey","download_url":"https://codeload.github.com/pubkey/async-test-util/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248190403,"owners_count":21062276,"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":["assert","async","async-await","jasmine","javascript","karma","mocha","testcafe","testing"],"created_at":"2024-09-24T19:50:23.631Z","updated_at":"2025-04-11T01:01:38.100Z","avatar_url":"https://github.com/pubkey.png","language":"JavaScript","readme":"# async-test-util\n\nUtility-functions that can be usefull when you have asynchronous tests in javascript.\n\n## Installation\n\n```sh\n$ npm install async-test-util --save-dev\n```\n\n```javascript\n// es6\nimport AsyncTestUtil from 'async-test-util';\n\n// es5\nvar AsyncTestUtil = require('async-test-util');\n```\n\n## wait()\n\nWaits until the given time has expired and then resolves.\n\n```javascript\nit('should wait', async() =\u003e {\n    await AsyncTestUtil.wait(200);\n    console.log('200 ms is over');\n});\n```\n\n## waitResolveable()\n\nWaits until the given timeout has expired or the resolve was triggered manually\n\n```javascript\nit('should wait until observable fired or time is over', async() =\u003e {\n    const resolveable = AsyncTestUtil.waitResolveable(200);\n    myObservable.subscribe(sth =\u003e {\n        console.log('got first event');\n        resolveable.resolve();\n    });\n    await resolveable.promise;\n});\n```\n\n## waitUntil()\n\nWaits until the given predicate-function returns a truthy value. Throws if the optional timeout has passed before.\n\n```javascript\nit('should wait until server is online', async() =\u003e {\n    const checkServer = async() =\u003e {\n        try{\n            await fetch('http://example.com/api/');\n            return true;\n        }catch(err) {\n            return false;\n        }\n    };\n    await AsyncTestUtil.waitUntil(checkServer);\n});\n```\n\nWith timeout:\n\n```javascript\nit('should wait until server is online (maxtime: 1000ms)', async() =\u003e {\n    const checkServer = async() =\u003e {\n        try{\n            await fetch('http://example.com/api/');\n            return true;\n        }catch(err) {\n            return false;\n        }\n    };\n    await AsyncTestUtil.waitUntil(checkServer, 1000);\n});\n```\n\n\nWith return value:\n\n```javascript\nit('should wait until server is online (maxtime: 1000ms)', async() =\u003e {\n    const checkServer = async() =\u003e {\n        try{\n            const response = await fetch('http://example.com/api/');\n            return await response.json();\n        }catch(err) {\n            return false;\n        }\n    };\n    const firstSuccessfullResponse = await AsyncTestUtil.waitUntil(checkServer, 1000);\n});\n```\n\n## waitForever()\n\nWaits forever, never resolves.\n\n```javascript\nit('should never resolve', async() =\u003e {\n    let resolved = false;\n    AsyncTestUtil\n        .waitForever()\n        .then(() =\u003e resolved = true);\n    await AsyncTestUtil.wait(100);\n    assert.equal(false, resolved);\n});\n```\n\n## runForever()\n\nRuns the given predicate-function forever. Between each run, the interval-time is awaited.\n\n```javascript\nit('should run forever', async() =\u003e {\n    let t = 0;\n    const pred = () =\u003e t++;\n    AsyncTestUtil.runForever(\n        pred, // predicate-function\n        10    // interval\n     );\n\n    await AsyncTestUtil.wait(100);\n    assert.ok(t \u003e 4);\n    const lastT = t;\n    await AsyncTestUtil.wait(100);\n    assert.ok(t \u003e lastT);\n});\n```\n\n## assertThrows()\n\nAsync-Form of [assert.throws](https://nodejs.org/api/assert.html#assert_assert_throws_fn_error_message). Asserts that the given function throws with the defined error, throws if not.\n\n```javascript\n// with error-type\nit('should throw because route does not exist', async() =\u003e {\n    const getServerVersion = async() =\u003e {\n        const response = await fetch('http://example.com/foobar/');\n        return response;\n    };\n    await AsyncTestUtil.assertThrows(\n        () =\u003e getServerVersion(),       // function that throws (required)\n        Error                   // Error-type           (optional)\n    );\n});\n\n// with error-text-flag\nit('should throw because route does not exist', async() =\u003e {\n    const pingServer = async() =\u003e {\n        try{\n            await fetch('http://example.com/foobar/');            \n        }catch(err) {\n            throw new Error('route not reachable');\n        }\n    };\n    await AsyncTestUtil.assertThrows(\n        () =\u003e pingServer(),       // function that throws                                    (required)\n        Error,                    // Error-type                                              (optional)\n        'reachable'               // text-flag, throw if error-message does not include this (optional)  \n    );\n\n    // or you can pass a string-array to ensure all is in error message\n    await AsyncTestUtil.assertThrows(\n        () =\u003e pingServer(),       // function that throws                                    (required)\n        Error,                    // Error-type                                              (optional)\n        ['route', 'reachable']    // text-flag, throw if error-message does not include this (optional)  \n    );\n});\n\n// assertThrows returns the error\nit('should have the custom error-property', async() =\u003e {\n    const throwingFunction = async()=\u003e{\n        const error = new Error('error message');\n        error.foo = 'bar';\n        throw error;\n    }\n    const thrown = await AsyncTestUtil.assertThrows(\n        () =\u003e pingServer(),       // function that throws                                    (required)\n        Error,                    // Error-type                                              (optional)\n        'message'               // text-flag, throw if error-message does not include this (optional)  \n    );\n    assert.equal(thrown.foo, 'bar');\n});\n```\n\n## resolveValues()\n\nRecieves an object with promises as values. Returns ans object with the resolved promises as values. Use this in test-setups to improve the test-speed by running everything in parallel.\n\n```javascript\n// instead of this\nconst database = await connectDatabase();\nconst user1 = await getUser();\nconst user2 = await getUser();\n\n// do this\nconst {\n    database,\n    user1,\n    user2\n} = await AsyncTestUtil.resolveValues({\n    database: connectDatabase();\n    user1: getUser();\n    user2: getUser();\n});\n```\n\n## isPromise()\n\nReturns true if the given value is a `Promise`;\n\n```javascript\nconst is = AsyncTestUtil.isPromise(myAsyncFunction()); // true\nconst is = AsyncTestUtil.isPromise('foobar'); // false\n```\n\n## promisify\n\nTransforms the given value to a promise if it was no promise before.\n\n```javascript\nconst ensurePromise = AsyncTestUtil.promisify(maybeAsyncFunction());\n\n// now you are sure this is a promise\nensurePromise.then(/* ... */)\n```\n\n## randomString()\n\nCreates a random string. Takes length as first parameter an custom charset as second.\n\n```javascript\nconsole.log(AsyncTestUtil.randomString());\n// \u003e 'rhfkx'\n\nconsole.log(AsyncTestUtil.randomString(10));\n// \u003e 'dhcvkledzu'\n\nconsole.log(AsyncTestUtil.randomString(\n    6,    // (optional) length\n    'abc' // (optional) charset, only this will be used to create the string\n));\n// \u003e 'acbcba'\n```\n\n## randomNumber()\n\nCreates a random number. Optional range can be given.\n\n```javascript\nconsole.log(AsyncTestUtil.randomNumber());\n// \u003e 56\n\nconsole.log(AsyncTestUtil.randomNumber(\n    1000, // min-value (default=0)\n    2000 // max-value (default=1000)\n));\n// \u003e 1768\n```\n\n## randomBoolean()\n\nCreates a random boolean. Returns `true` or `false`.\n\n```javascript\nconsole.log(AsyncTestUtil.randomBoolean());\n// \u003e true\n```\n\n## clone()\n\nReference to [clone](https://www.npmjs.com/package/clone). Does exactly the same thing.\n\n```javascript\nit('should not modify the original object', () =\u003e {\n    const original = {\n        foo: 'bar',\n        level: 1\n    };\n    const cloned = AsyncTestUtil.clone(original);\n    cloned.level = 2;\n    assert.equal(original.level, 1);\n});\n```\n\n## deepEqual()\n\nReference to [deep-equal](https://www.npmjs.com/package/deep-equal). Does exactly the same thing.\n\n```javascript\nit('the 2 objects should be equal', () =\u003e {\n    const obj1 = {\n        foo: 'bar',\n        level: 1\n    };\n    const obj2 = {\n        foo: 'bar',\n        level: 1\n    };\n    assert.ok(AsyncTestUtil.deepEqual(obj1, obj2));\n});\n```\n\n## performanceNow()\n\nWorks equal to [performance.now](https://developer.mozilla.org/de/docs/Web/API/Performance/now) but works in browsers and nodeJs.\n\n```javascript\nit('should take less then 200 milliseconds', () =\u003e {\n    const now = AsyncTestUtil.performanceNow(); // in milliseconds\n    await doSomething();\n    const later = AsyncTestUtil.performanceNow(); // in milliseconds\n    assert.ok((now + 50 * 1000 ) \u003e later);\n});\n```\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpubkey%2Fasync-test-util","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpubkey%2Fasync-test-util","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpubkey%2Fasync-test-util/lists"}