{"id":20682257,"url":"https://github.com/j-fischer/js-mock","last_synced_at":"2025-07-12T12:37:22.104Z","repository":{"id":39787366,"uuid":"45283681","full_name":"j-fischer/js-mock","owner":"j-fischer","description":"Javascript mocking library for any test framework","archived":false,"fork":false,"pushed_at":"2022-12-06T20:24:21.000Z","size":1589,"stargazers_count":7,"open_issues_count":8,"forks_count":3,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-04-13T01:57:59.670Z","etag":null,"topics":["javascript","mocking-framework","nodejs","salesforce-lightning"],"latest_commit_sha":null,"homepage":"http://www.jsmock.org","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-3-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/j-fischer.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2015-10-31T00:56:29.000Z","updated_at":"2020-07-22T17:55:00.000Z","dependencies_parsed_at":"2022-08-31T00:01:57.032Z","dependency_job_id":null,"html_url":"https://github.com/j-fischer/js-mock","commit_stats":null,"previous_names":[],"tags_count":18,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/j-fischer%2Fjs-mock","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/j-fischer%2Fjs-mock/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/j-fischer%2Fjs-mock/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/j-fischer%2Fjs-mock/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/j-fischer","download_url":"https://codeload.github.com/j-fischer/js-mock/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250237851,"owners_count":21397403,"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":["javascript","mocking-framework","nodejs","salesforce-lightning"],"created_at":"2024-11-16T22:13:09.040Z","updated_at":"2025-04-22T12:20:49.877Z","avatar_url":"https://github.com/j-fischer.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# JsMock\n\n[![Build Status](https://travis-ci.org/j-fischer/js-mock.svg?branch=master)](https://travis-ci.org/j-fischer/js-mock) [![Coverage Status](https://coveralls.io/repos/github/j-fischer/js-mock/badge.svg?branch=master)](https://coveralls.io/github/j-fischer/js-mock?branch=master)\n\nA JavaScript mocking framework, which can be used with any test framework. JsMock is inspired by [jMock](http://www.jmock.org/) and [Sinon.js](http://sinonjs.org/)\nwith its interface being very similar to Sinon in order to make it easy to switch between those two frameworks.\n\nJsMock should work with any test framework.\n\n## How is JsMock different from other mock frameworks?\n\nJsMock only supports mock objects where the expectations have to be defined before the mock objects\nare used by the function/module under test. This may require a bit more effort when writing a test case,\nbut the outcome should be that the interactions of the unit under test with the mock object are very clearly\ndefined through the tests. This should expose bugs or unintended behavior that would otherwise remain hidden\nif stubs or spies are used, but not evaluated properly.\n\nJsMock also has the goal to simplify the setup and validation of mocks by monitoring them for you.\nThis will make it easy to evaluate that all expected calls have been made at the end of a test.\n\n## Installation\n\nInstall JsMock via [npm](https://www.npmjs.com)\n\n    $ npm install js-mock --save-dev\n\nand include node_modules/js-mock/dist/js-mock.js in your project.\n\n## Getting Started\n\nThe following list highlights some simple use cases of JsMock and includes some best practices.\nFor a full reference, please check out the [API docs](http://www.jsmock.org/docs/index.html) or\ntake a look at the [unit tests](https://github.com/j-fischer/js-mock/src/test/javascript).\n\n### Include JsMock in Your Tests\n\n```\n//ES6 module import\nimport JsMock from 'js-mock';\n\n//ES5 module import\nvar JsMock = require('js-mock').default;\n```\n\n### JsMock.mock()\n\nJsMock can create mock functions or objects.\n\n    var mockFunc = JsMock.mock(\"nameOfFunction\");\n\n    var objectToMock = {\n      doSomething: function () {\n        // does something\n      }\n    };\n\n    // Note: Returns a mock clone, the original object will not be modified.\n    var mockObject = JsMock.mock(\"nameOfObject\", objectToMock);\n\n    // It's possible to also pass in other libraries, but the original will not be replaced in this case\n    var jqueryMock = JsMock.mock(\"$\", $);\n\n### JsMock.mockGlobal()\n\nJsMock can also replace global variables with a mock object and restore the original at any time. The global mock\nwill automatically be activated, meaning that the global reference was replaced with the mock object.\nLike any other mock object, the global mock can be verfied at any time with a single call.\n\n    var jqueryMock = JsMock.mockGlobal(\"$\");\n\n    jqueryMock.expect().ajax.once();\n\n    // Fulfill the expectation\n    $.ajax();\n\n    // Restore jQuery to be the original API and not the mock anymore.\n    // This will also verify that all expectations have been fulfilled\n    jqueryMock.restore();\n\nMore examples on how to use `JsMock.mockGlobal()` can be found in its [test file](https://github.com/j-fischer/js-mock/blob/master/src/test/javascript/mockGobal.spec.js).\n\n### JsMock.watch()\n\nWhen testing a module or file, the best way is to define a set of global mocks using the `watch()` function,\nwhich can be shared between the test cases. All mocks created inside the factory function will be added to the current\ntest context and can be verified with a single call to `JsMock.assertWatched()`.\n\n    var mockFunction1, mockFunction2;\n    JsMock.watch(function () {\n      mockFunction1 = JsMock.mock(\"name1\");\n      mockFunction2 = JsMock.mock(\"name2\");\n    });\n\n\n### JsMock.assertWatched()\n\nCalling this function will go through the list of all mocks that are currently monitored and will call `.verify()` on each of them.\nShould a mock fail the validation, an `ExpectationError` will be thrown. The functions returns `true` if all mocks were satisfied,\nwhich can be used to pass a simple assertion. Any monitored global mock will also be restored when `.assertWatched()` is called.\n\n    var mockFunction1, mockFunction2, jQueryMock;\n    JsMock.watch(function () {\n      mockFunction1 = JsMock.mock(\"name1\");\n      mockFunction2 = JsMock.mock(\"name2\");\n\n      jQueryMock = JsMock.mockGlobal(\"$\");\n    });\n\n    // Verify all monitored mocks and restore globals\n    JsMock.assertWatched();\n\nIf the test case requires an assertion, the following could be done:\n\n    var mockFunction1;\n    JsMock.watch(function () {\n      mockFunction1 = JsMock.mock(\"name1\");\n    });\n\n    // Verify all monitored mocks\n    assert.ok(JsMock.assertWatched());\n\n\n### mock.exactly(\u003cnumber\u003e)\n\nSet the expectation for the mock to be called N number of times.\n\n    var mock = JsMock.mock(\"aMock\");\n\n    // Expect the mock to be invoked 4 times\n    mock.exactly(4);\n\n\n### mock.with(\u003canything\u003e...)\n\nSet the expectation to be called with the exact arguments provided. Any of the given arguments can be\na Hamjest style matcher. If a matcher is provided as an argument, the actual argument will\nbe passed on to the `matches()` function of the matcher object.\n\n    var mock = JsMock.mock(\"aMock\");\n\n    // Expect to be called like this: mock(\"foo\", \"bar\");\n    mock.once().with(\"foo\", \"bar\");\n\n\n### mock.returns(\u003canything\u003e)\n\nSet the expectation for the mock to return a given value.\n\n    var mock = JsMock.mock(\"aMock\");\n\n    // Expect the mock to be invoked once with no arguments, returning \"foo\"\n    mock.once().with().returns(\"foo\")\n\n    var x = \"foo\" === mock(); // true\n\n### mock.throws(\u003cstring or object\u003e)\n\nSet the expectation for the mock to the given exception.\n\n    var mock = JsMock.mock(\"aMock\");\n\n    // Expect the mock to be invoked once with no arguments\n    mock.once().with().throws(new Error(\"foo\"))\n\n    mock(); // will throw an Error with the message \"foo\"\n\n### mock.will(\u003cfunction\u003e)\n\nWill execute the given function once the mock was successfully called. The arguments passed to the mock function\nwill be forwarded to the provided function and the value returned by the given function will also be returned by the mock.\n\n    var mock = JsMock.mock(\"aMock\");\n\n    // Expect the mock to be invoked once with any arguments\n    mock.once().will(function (arg) {\n      var x = arg; // x == \"foo\"\n      return x + \"bar\";\n    });\n\n    var y = mock(\"foo\"); // y == \"foobar\"\n\n### mock.willThrow(\u003cfunction\u003e)\n\nExecutes a function if the mock was successfully matched. All arguments passed in to the mock function\nwill be passed on to the function defined in here. The function will be executed immediately and is\nexpected to throw an exception. If it does not throw and expection, an ExpectationError will be thrown.\n\n    var mock = JsMock.mock(\"aMock\");\n\n    mock.once().willThrow(function (arg) {\n      var x = arg; // x == \"foo\"\n      return new Error(\"bar\");\n    });\n\n    mock(\"foo\"); // will throw an Error with the message \"bar\"\n\n### mock.onCall(\u003cnumber\u003e)\n\nWill set all following expectations for the given call.\n\n    var mock = JsMock.mock(\"aMock\");\n\n    // Expect the mock to be invoked 2 times\n    mock.exactly(2);\n\n    // On the first call, expect \"foo\" to be the argument and return 1\n    mock.onCall(1).with(\"foo\").returns(1);\n\n    // On the second call, expect \"bar\" to be the argument and return 2\n    mock.onCall(2).with(\"bar\").returns(2);\n\n### mock.allowing()\n\nConverts this mock into a stub, which will never throw a missing invocation error.\nAs a stub, it cannot have different behaviors for different calls. If `withExactArgs`\nis defined, any invocation other than the defined one will throw an unexpected invocation error.\nNote: Verifying the stub will reset the object into mocking mode with 0 calls expected.\n\n    var mock = JsMock.mock(\"aMock\");\n\n    // Allows the mock to be invoked as often as possible\n    mock.allowing();\n\n    mock(\"foo\");\n    mock(\"bar\");\n\n    // will always succeed and reset the mock\n    mock.verify();\n\n### mock.verify()\n\nVerifies that all expectations of this mock have been fulfilled. If any expectation was\nnot fullfiled, an ExpectationError will be thrown.\n\n    var mock = JsMock.mock(\"aMock\");\n\n    // Expect the mock to be invoked once\n    mock.once();\n\n    // will throw an ExpectationError\n    mock.verify();\n\nIf the test case requires an assertion, the following could be done:\n\n    var mock = JsMock.mock(\"aMock\");\n\n    // Expect the mock to be invoked once\n    mock.once();\n\n    mock();\n\n    // Verify all expectations of this mock\n    assert.ok(mock.verify());\n\n\n### Aliases and Helpers\n\nThe following functions are helpers that will map their calls to the API functions above.\n\n    mock.never() // instead of .exactly(0)\n    mock.once() // instead of .exactly(1)\n    mock.twice() // instead of .exactly(2)\n    mock.thrice() // instead of .exactly(3)\n\n    mock.onFirstCall() // instead of .onCall(1)\n    mock.onSecondCall() // instead of .onCall(2)\n    mock.onThirdCall() // instead of .onCall(3)\n\n    mock.withExactArgs(\u003canything\u003e...) // instead of .with(\u003canything\u003e...)\n\n\n## Frameworks and Best Practices\n\nWhile JsMock is test framework independent, there are best practices when using it with a framework. In general, it is important to understand how the test framework\nloads and executes its tests. Especially when `JsMock.watch()` is used, it is crucial to ensure that it governs the context of the current test file, otherwise\nyour tests may pass with unfulfilled expecations. Below are some examples on how to use JsMock with [Jasmine](http://jasmine.github.io/2.0/introduction.html) and [QUnit](https://qunitjs.com/).\n\n### Jasmine\n\n    describe(\"A Test\", function {\n\n      var mockFunc, jQueryMock;\n\n      beforeEach(function () {\n        JsMock.watch(function () {\n          mockFunc = JsMock.mock(\"mockFunc\");\n          jQueryMock = JsMock.mockGlobal(\"$\");\n        }\n      });\n\n      afterEach(JsMock.assertWatched);\n\n      it (\"test 1\", function() {\n        // set expectations and test\n      });\n\n      it (\"test 2\", function() {\n        // set expectations and test\n      });\n    });\n\n### QUnit\n\n    var mockFunc, jQueryMock;\n\n    QUnit.module(\"A test\", {\n      beforeEach: function () {\n        JsMock.watch(function () {\n          mockFunc = JsMock.mock(\"mockFunc\");\n          jQueryMock = JsMock.mockGlobal(\"$\");\n        }\n      },\n      afterEach: function (assert) {\n        assert.ok(JsMock.assertWatched());\n      }\n    });\n\n    QUnit.test(\"test 1\", function(assert) {\n      // set expectations and test\n    });\n\n    QUnit.test(\"test 2\", function(assert) {\n      // set expectations and test\n    });\n\n### Hamjest\n\nWhile JsMock does not have any dependencies, it does support [Hamjest](https://github.com/rluba/hamjest) for the\nmatching of arguments when using `with()` or `withExactArgs()`. Hamjest has a vast number of existing matchers that can be used to\nvalidate an argument. And should there not be the right matcher available, you can [easily write your own implementation](https://github.com/rluba/hamjest/wiki/Custom-matchers).\n\n    var mock = JsMock.mock(\"aMock\");\n\n    mock.once().with(hamjest.contains(\"foo\", \"bar\"));\n\n    mock([\"foo\", \"bar\"]);\n    mock.verify();\n\n    mock.thrice().with(hamjest.greaterThan(3));\n\n    mock(4);\n    mock(6);\n    mock(7);\n\n    mock.verify();\n\n## API Docs\n\nThe full API documentation can be found [here](http://www.jsmock.org/docs/index.html).\n\n## License\n\nBSD 3-clause, see [License.txt](https://github.com/j-fischer/js-mock/blob/master/LICENSE.txt)\n\n[![js-api generator](http://img.shields.io/badge/Powered%20by-%20JS%20API%20Generator-green.svg?style=flat-square)](https://www.npmjs.com/package/generator-js-api)\n\n## Changelog\n\n### 2.0.0\n\n- Removed built-in dependency on JsHamcrest, it can still be used to pass a Matcher as an argument\n- Removed Mock.withEquivalentArray()  \n- Removed Mock.withEquivalentObject()\n- HamJest matchers are now supported\n- Improved error messages for unexpected invocations of a Mock\n- Added ES6 support through Babel compiler\n\nFor older versions, please read the [CHANGELOG.md](https://github.com/j-fischer/js-mock/blob/master/CHANGELOG.md) file.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fj-fischer%2Fjs-mock","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fj-fischer%2Fjs-mock","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fj-fischer%2Fjs-mock/lists"}