{"id":19773960,"url":"https://github.com/badoo/mockjs","last_synced_at":"2025-07-06T01:37:11.371Z","repository":{"id":5622467,"uuid":"6830259","full_name":"badoo/MockJS","owner":"badoo","description":null,"archived":false,"fork":false,"pushed_at":"2012-11-29T13:33:33.000Z","size":125,"stargazers_count":68,"open_issues_count":1,"forks_count":9,"subscribers_count":17,"default_branch":"master","last_synced_at":"2024-04-20T17:45:51.884Z","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":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/badoo.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2012-11-23T16:38:25.000Z","updated_at":"2024-01-31T14:33:46.000Z","dependencies_parsed_at":"2022-08-30T19:20:27.145Z","dependency_job_id":null,"html_url":"https://github.com/badoo/MockJS","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/badoo%2FMockJS","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/badoo%2FMockJS/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/badoo%2FMockJS/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/badoo%2FMockJS/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/badoo","download_url":"https://codeload.github.com/badoo/MockJS/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":224219555,"owners_count":17275477,"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-11-12T05:11:37.846Z","updated_at":"2024-11-12T05:11:38.460Z","avatar_url":"https://github.com/badoo.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"MockJS\n========\n\nJavaScript object mocking library based on Mockito syntax for JS unit testing.\nIt goes a bit further by implementing some cool syntax you can achieve in JavaScript using ECMA5 object properties and allowing you to handle mocking global scope functions and match calls on different contexts.\n\n\n**Installation**\n\n- Include /src/Mock.js into your tests runtime\n- Mock will automatically attach itself to the \"window\" scope (browser) if it exists\n\nFor specific unit testing tools:\n\n- you can use Mock.hookTo(context); to import MockJS tools into your testing scope.\n- Currently supports context = \"screwunit\", \"JsUnitTest\", \"jsUnity\", \"jSpec\", \"JsTestDriver\", \"YUITest\", \"QUnit\";\n\nOr you can send your own context object:\n\n```javascript\nMock.hookTo(MyTestingTool.globalTestScope);\n```\n\nQuick test / check:\n\n- check and run /testception/index.html in your browser (outputs test results in console)\nNote: the small *TestSuite* included in testception is a very simplistic tool used to test MockJS itself - MockJS is completely standalone.\n\nDocumentation\n========\nDocumentation below is divided into 2 main sections:\n\n- Mockito Classics - what you did in Mockito and how to do it in MockJS;\n- MockJS Specifics - specific features for mocking JavaScript;\n\nDocs 1. Mockito Classics\n========\nYour Mockito classics (rewritten directly from [Mockito's documentation](http://docs.mockito.googlecode.com/hg/latest/org/mockito/Mockito.html \"Mockito's documentation\")):\n\n**\u003ca href=\"#1\"\u003e1\u003c/a\u003e. Verify interactions**\n\n```javascript\nvar mockArray = Mock([]);   //create the mock object\n\nmockArray.push(\"one\");\n\nverify( Acts.once, mockArray.push(\"one\") );\n```\n\n**\u003ca href=\"#1\"\u003e1\u003c/a\u003e. Stubbing method calls**\n\n```javascript\nwhen( mockArray.push(\"one\") ).thenReturn(1);\n\nconsole.log( mockArray.push(\"one\") );   //prints \"1\"\n\nverify( Acts.once, mockArray.push(\"one\") );\n```\n\n**\u003ca href=\"#3\"\u003e3\u003c/a\u003e. Argument matchers**\n\n```javascript\nwhen( mockArray.push(Match.anything) ).thenReturn(\"hello!\");\n\nconsole.log( mockArray.push(\"one\") );   //prints \"hello!\"\nconsole.log( mockArray.push(999) );   //prints \"hello!\"\n    \n//look into 102. for more information\n```\n\n**\u003ca href=\"#4\"\u003e4\u003c/a\u003e. Verifying exact number of invocations / at least x / never**\n\n```javascript\nverify( Acts.never, mockArray.push(\"one\") );        //ok\n    \nmockArray.push(\"one\");\nverify( Acts.once, mockArray.push(\"one\") );         //ok\nverify( Acts.atLeast(1), mockArray.push(\"one\") );   //ok\n    \nmockArray.push(\"one\");\nmockArray.push(\"one\");\nverify( Acts.atMost(2), mockArray.push(\"one\") );    //fails\n    \n//look into 103. for more information\n```\n\n**\u003ca href=\"#5\"\u003e5\u003c/a\u003e. Stubbing void methods with exceptions**\n\n```javascript\nwhen( mockArray.push(Match.anything) ).thenThrow(\"Hi, I am an expcetion\");\n    \nmockArray.push(\"something\");    //throws our exception\n```\n\n**\u003ca href=\"#11\"\u003e11\u003c/a\u003e. Stubbing with callbacks**\n\n```javascript\nwhen( mockArray.push(Match.anything) ).thenReturn(function(arg){ \n    console.log(\"array.push('\"+arg+\"') called!\");\n    return \"hello!\"; \n});\n    \nconsole.log( mockArray.push(\"one\") );   //prints \"array.push('one') called!\" and \"hello!\"\n```    \n\n**\u003ca href=\"#12\"\u003e12\u003c/a\u003e. thenReturn() | thenThow() | thenAnswer() | thenNothing() | thenCallRealMethod() family of methods**\n\n*Currently implemented:*\n\n- thenReturn()\n- thenThow()\n\n*Not Yet Implemented:*\n\n- thenNothing()\n- thenCallRealMethod()\n\nUnnecessary in JS: thenAnswer()\n\n**\u003ca href=\"#15\"\u003e15\u003c/a\u003e. Capturing arguments for further assertions**\n\n//All return callbacks support it by default - take a look at example [11.](#11)\n\n\u003c!--\n**\u003ca href=\"#17\"\u003e17\u003c/a\u003e. Resetting mocks**\n    \n//Ongoing work\n\nMock.resetVerifies(mockArray [, context]);      \\\\will clear the number of calls (all methods), optionally on a specific context (see [101.](#101))\nMock.reset(mockArray [, context]);              \\\\will clear all stubs and number of calls\n--\u003e\n\n**\u003ca href=\"#18\"\u003e18\u003c/a\u003e. Troubleshooting \u0026 validating framework usage**\n\nYou should know that MockJS validates if you use it correctly **all the time**.\nYou have more questions please refer to our issues section on github.\n\n**\u003ca href=\"#26\"\u003e26\u003c/a\u003e. Mocking details**\n\n```javascript\nMock.isMock(someObject);\n```\n   \n*Not Yet Implemented:*\n\n- Mock.isSpy \n\n\n\nDocs 2. MockJS specific features\n=======\n\n**\u003ca href=\"#100\"\u003e100\u003c/a\u003e. Mock in-scope functions**\n\n```javascript\nfunction sum(a, b){\n    return a+b;\n}\n    \nvar mockSum = Mock(sum);\n    \nmockSum(5, 5); //returns undefined (default)\n```\n\n**\u003ca href=\"#101\"\u003e101\u003c/a\u003e. Match contexts**\n    \n```javascript\nwhen( mockArray.push.apply(Match.anyContext, [Match.anything]) ).thenReturn(\"something\");\n    \nmockArray.push.apply([], [\"one\"]);\n    \nverify( Acts.once, mockArray.push.apply(Match.anyContext, [Match.anything]) );\n```\n    \n**\u003ca href=\"#102\"\u003e102\u003c/a\u003e. Matchers (Match)**\n    \n```javascript\n//argument matchers\nMatch.anyString         //argument is a string\nMatch.anyInt            //argument is an integer\nMatch.anyNumber         //argument is a number\nMatch.anyFunction       //argument is a function\nMatch.anything          //argument is not undefined  \n    \nMatch.everything        //special matcher - all arguments from this point on will be accepted\n                        //eg. when( foo(\"a\", Match.everything) ) will match foo(\"a\"), foo(\"a\", \"one\"), foo(\"a\", 1, 2, 3, 4, 5, 6);\n                            \n                            \n//context matcher\nMatch.anyContext        //all contexts will be accepted\n```\n    \n**\u003ca href=\"#103\"\u003e103\u003c/a\u003e. Call Counters (Acts)**\n    \n```javascript\nActs.times(x);  //verifies call acted exactly x number of times\nActs.never      //never happens (short for Acts.times(0))\nActs.once       //acts once (short for Acts.times(1))\nActs.atLeast(x) //acts at least x times\nActs.atMost(x)  //acts at most x times\n    \n//Note: the following syntax should not be used:\nvar a = Acts.never\nverify( a, foo() );                 //works 1st time\nverify( a, foo(\"one\") );            //throws unexpected action in MockJS on all further uses\n    \n    \nverify( Acts.never, foo(\"one\") );   //always use the complete API syntax\n```\n    \n\n**\u003ca href=\"#104\"\u003e104\u003c/a\u003e. Custom argument matchers**\n    \n```javascript\nfunction myClass(){\n}\n    \nvar matchObjectClass = function(arg){\n    return arg instanceof myClass;\n}\n    \nwhen( foo(matchObjectClass) ).thenReturn(\"something\");\n    \nfoo(new myClass());  //returns \"something\"\n    \nverify( Acts.once, foo(matchObjectClass) ); //verifies correctly\n```\n    \n**\u003ca href=\"#105\"\u003e105\u003c/a\u003e. Save and restore global references**\n\n```javascript\n//let's consider our global function foo\nvar foo = function(a){\n    alert(a);\n    return \"hello\";\n}\n    \nfoo = Mock.andSave(foo, \"myFoo\");        //mocks function foo but keeps a reference for teardown (below)\n    \nwhen( foo(Match.anything) ).thenReturn(\"hello\");\n    \nconsole.log( foo(\"hey\") );         //prints \"hello\" into console\n    \n    \n//teardown\nfoo = Mock.teardown(\"myFoo\");    //sets foo back to the original function\n    \nfoo(\"hey\");         //alerts \"hey\"\n```\n    \n**\u003ca href=\"#106\"\u003e106\u003c/a\u003e. Mock.new() - create mocks for inacessible objects**\n\n```javascript\n//Consider the function we need to mock:\nfunction $(a){ \n    var privateObject = {\n        whisper:function(){\n            console.log(a);\n            return true;\n        },\n        say:function(){\n            alert(a);\n            return true;\n        }   \n    }\n        \n    return privateObject;\n}\n// Notice we cannot get a \"mockable\" instance of privateObject\n// but we do know it is going to have a method \"say\"\n    \n//our function being tested\nfunction iNeedTesting(){\n    var check = $(\"hello\");\n        \n    if(check.whisper() \u0026\u0026 check.say()) console.log(\"works!\");\n}\n    \n    \n    \n    \n//let's mock the main wrapper\n$ = Mock($);\n    \nvar privateObject = Mock.new([\"whisper\", \"say\"]);       //create a mock object with methods \"whisper\" and \"say\"\n    \nwhen( $(\"hello\") ).thenReturn(mockPrivateObject);\nwhen( privateObject.whisper() ).thenReturn(true);\nwhen( privateObject.say() ).thenReturn(true);\n    \niNeedTesting(); //run our function being tested - prints out \"works!\" to console\n    \nverify(Acts.once, $(\"hello\"));\nverify(Acts.once, privateObject.whisper());\nverify(Acts.once, privateObject.say());\n    \n//all ok\n```\n    \n\nOther Mockito features status\n========\nStuff on Mockito documentation that we haven't implemented yet\n\n- **6. Verification in order**\n- **7. Making sure interaction(s) never happened on mock**\n- **8. Finding redundant invocations**\n- **10. Stubbing consecutive calls (iterator-style stubbing)**\n- **13. Spying on real objects**\n- **14. Changing default return values of unstubbed invocations**\n- **16. Real partial mocks**\n- **17. Resetting mocks**\n- **19. Aliases for behavior driven development**\n- **20. Serializable mocks**\n- **21. New annotations: @Captor, @Spy, @InjectMocks** *//Note: Probably Not Applicable*\n- **22. Verification with timeout**\n- **23. Automatic instantiation of @Spies, @InjectMocks and constructor injection goodness** *//Note: Probably Not Applicable*\n- **24. One-liner stubs**\n- **25. Verification ignoring stubs**\n- **27. Delegate calls to real instance** *//Note: Probably Not Applicable*\n- **28. MockMaker API** *//Note: Probably Not Applicable*\n\nSomething extra we would like to do:\n\n- **107. Make it available as a npm package (Node.js)**\n\nPull requests anyone? :p\n\nCredits\n=====\n\nThis special cocktail is brought to you by [Badoo Trading Limited](http://corp.badoo.com \"Badoo Trading Limited\") and it is released under the [MIT License](http://copyfree.org/licenses/mit/license.txt \"MIT License\") \n\nCreated by [Carlos Ouro](https://github.com/carlosouro/ \"Carlos Ouro\")","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbadoo%2Fmockjs","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbadoo%2Fmockjs","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbadoo%2Fmockjs/lists"}