[
  {
    "path": ".editorconfig",
    "content": "# top-most EditorConfig file\nroot = true\n\n# Unix-style newlines with a newline ending every file\n[*]\nindent_style = space\nindent_size = 4\nend_of_line = lf\ncharset = utf-8\ntrim_trailing_whitespace = true\ninsert_final_newline = true\n\n[*.md]\ntrim_trailing_whitespace = false\n"
  },
  {
    "path": ".gitignore",
    "content": "# Ignore Visual Studio  Project #\n###################\n*.user\n*.gpState\n*.suo\nbin\nobj\n/packages\n\n# Ignore Node & Bower\n###################\nnode_modules\n/src/client/build\n/src/build\nbower_components\n/report\n**/test/coverage\n\n# mongo db\n###################\n#Don't commit Mongo Database files\n*.lock\n*.0\n*.1\n*.ns\njournal\n\n# Ignore Web Storm #\n.idea\n\n# Compiled source #\n###################\n*.com\n*.class\n*.dll\n*.exe\n*.o\n*.so\n\n# Packages #\n############\n# it's better to unpack these files and commit the raw source\n# git has its own built in compression methods\n*.7z\n*.dmg\n*.gz\n*.iso\n*.jar\n*.rar\n*.tar\n*.xap\n*.zip\n\n# Logs and databases #\n######################\n*.log\n*.sql\n*.sqlite\n# *.sdf\n*.mdf\n*.ldf\n\n# OS generated files #\n######################\n.DS_Store*\nehthumbs.db\nIcon?\nThumbs.db\npackages\n~$*.pp*\n\n# Plato generated files #\n######################\n/report\n\n# Meteor #\n#####################\n.versions\n"
  },
  {
    "path": ".jscsrc",
    "content": "{\n    \"excludeFiles\": [\"node_modules/**\", \"bower_components/**\"],\n\n    \"requireCurlyBraces\": [\n        \"if\",\n        \"else\",\n        \"for\",\n        \"while\",\n        \"do\",\n        \"try\",\n        \"catch\"\n    ],\n    \"requireOperatorBeforeLineBreak\": true,\n    \"requireCamelCaseOrUpperCaseIdentifiers\": true,\n    \"maximumLineLength\": {\n      \"value\": 100,\n      \"allowComments\": true,\n      \"allowRegex\": true\n    },\n    \"validateIndentation\": 4,\n    \"validateQuoteMarks\": \"'\",\n\n    \"disallowMultipleLineStrings\": true,\n    \"disallowMixedSpacesAndTabs\": true,\n    \"disallowTrailingWhitespace\": true,\n    \"disallowSpaceAfterPrefixUnaryOperators\": true,\n    \"disallowMultipleVarDecl\": null,\n\n    \"requireSpaceAfterKeywords\": [\n      \"if\",\n      \"else\",\n      \"for\",\n      \"while\",\n      \"do\",\n      \"switch\",\n      \"return\",\n      \"try\",\n      \"catch\"\n    ],\n    \"requireSpaceBeforeBinaryOperators\": [\n        \"=\", \"+=\", \"-=\", \"*=\", \"/=\", \"%=\", \"<<=\", \">>=\", \">>>=\",\n        \"&=\", \"|=\", \"^=\", \"+=\",\n\n        \"+\", \"-\", \"*\", \"/\", \"%\", \"<<\", \">>\", \">>>\", \"&\",\n        \"|\", \"^\", \"&&\", \"||\", \"===\", \"==\", \">=\",\n        \"<=\", \"<\", \">\", \"!=\", \"!==\"\n    ],\n    \"requireSpaceAfterBinaryOperators\": true,\n    \"requireSpacesInConditionalExpression\": true,\n    \"requireSpaceBeforeBlockStatements\": true,\n    \"requireLineFeedAtFileEnd\": true,\n    \"disallowSpacesInsideObjectBrackets\": \"all\",\n    \"disallowSpacesInsideArrayBrackets\": \"all\",\n    \"disallowSpacesInsideParentheses\": true,\n\n    \"validateJSDoc\": {\n        \"checkParamNames\": true,\n        \"requireParamTypes\": true\n    },\n\n    \"disallowMultipleLineBreaks\": true,\n\n    \"disallowCommaBeforeLineBreak\": null,\n    \"disallowDanglingUnderscores\": null,\n    \"disallowEmptyBlocks\": null,\n    \"disallowMultipleLineStrings\": null,\n    \"disallowTrailingComma\": null,\n    \"requireCommaBeforeLineBreak\": null,\n    \"requireDotNotation\": null,\n    \"requireMultipleVarDecl\": null,\n    \"requireParenthesesAroundIIFE\": true\n}\n"
  },
  {
    "path": ".jshintrc",
    "content": "{\n    \"bitwise\": true,\n    \"camelcase\": true,\n    \"curly\": true,\n    \"eqeqeq\": true,\n    \"es3\": false,\n    \"forin\": true,\n    \"freeze\": true,\n    \"immed\": true,\n    \"indent\": 4,\n    \"latedef\": \"nofunc\",\n    \"newcap\": true,\n    \"noarg\": true,\n    \"noempty\": true,\n    \"nonbsp\": true,\n    \"nonew\": true,\n    \"plusplus\": false,\n    \"quotmark\": \"single\",\n    \"undef\": true,\n    \"unused\": false,\n    \"strict\": false,\n    \"maxparams\": 10,\n    \"maxdepth\": 5,\n    \"maxstatements\": 40,\n    \"maxcomplexity\": 8,\n    \"maxlen\": 120,\n\n    \"asi\": false,\n    \"boss\": false,\n    \"debug\": false,\n    \"eqnull\": true,\n    \"esnext\": false,\n    \"evil\": false,\n    \"expr\": false,\n    \"funcscope\": false,\n    \"globalstrict\": false,\n    \"iterator\": false,\n    \"lastsemic\": false,\n    \"laxbreak\": false,\n    \"laxcomma\": false,\n    \"loopfunc\": true,\n    \"maxerr\": false,\n    \"moz\": false,\n    \"multistr\": false,\n    \"notypeof\": false,\n    \"proto\": false,\n    \"scripturl\": false,\n    \"shadow\": false,\n    \"sub\": true,\n    \"supernew\": false,\n    \"validthis\": false,\n    \"noyield\": false,\n\n    \"browser\": true,\n    \"node\": true,\n\n    \"globals\": {\n        \"angular\": false\n    }\n}\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "bardjs Change Log\n===================\n### 0.1.10\n- no functional changes.\n- sinon moved its release file so we are now using bower to get sinon directly. which is better, anyway\n\n### 0.1.8\n- no functional changes.\n- reversed 0.1.7. Apparently [peerDependecies are a horrible idea](https://github.com/npm/npm/issues/5080) and have been deprecated. It also seems that bardjs is DIRECTLY dependent on sinon so it's back to being a dependency.\n\n### 0.1.7\n- no functional changes.\n- made sinon a [peerDependency](http://blog.nodejs.org/2013/02/07/peer-dependencies/) in npm package.json rather than a dependency. This changes means sinon is installed side-by-side bardjs (where you need it) rather than within bardjs's\nown node_modules folder.\n\n### 0.1.6\n- no functional changes\n- updated package.json and bower.json descriptions to make clear that bardjs works w/ Jasmine and QUnit too\n- removed package.json install script that invoked bower ... which might not be installed by those who load bard with npm\n\n### 0.1.5\n- no functional changes\n- added explanatory comments to $state and $route router fakes\n\n### 0.1.4\n- updated dependency versioning\n\n### 0.1.3\n- documentation about dependence on sinon\n- more robust handling of `this` when not using mocha; see [issue #5](https://github.com/wardbell/bardjs/issues/5).\n\n### 0.1.2\n- handle services that have prototype methods/attributes; see\n[pr #4](https://github.com/wardbell/bardjs/pull/4).\n\n### 0.1.1\n- incorporate `Function.bind` polyfill (for testing in phantom.js)\n\n### 0.1.0\n- added brackets code snippets (draft)\n\n### 0.0.9\n- added comments to make clear that `bard.appModule` should NOT be used if you'll be testing router services because it fakes their providers and that can't be reversed. Use regular `angular.mock.module` instead as directed.\n\n### 0.0.8\n- bard.inject should work for QUnit too (removed mocha/jasmine limitation).\n- Need QUnit tests.### 0.0.6\n- heavily revamped bard.inject. added diagnostic bard.debug\n\n### 0.0.7\n- bard.inject no longer uses evil Function; added addGlobals, mochaRunnerListener\n\n### Coming Soon\n"
  },
  {
    "path": "LICENSE",
    "content": "The MIT License (MIT)\n\nCopyright (c) 2014, 2015 Ward Bell\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# bardjs Test Helpers\n[![NPM version](https://img.shields.io/npm/v/bardjs.svg?style=flat)](https://www.npmjs.com/package/bardjs)\n\n**bardjs** is a small library of functions to help you write **Angular v.1.x application tests** ... whether you write them in [mocha](http://mochajs.org/ \"mochajs\") or [jasmine](http://jasmine.github.io/ \"jasmine\") or [QUnit](http://qunitjs.com/ \"QUnit\").\n\nWhat kind of help? Help with **routine tasks** that would otherwise clutter your tests and obscure their intent. \n\nThe poster child in this respect is the [`inject` method](#inject).  It can easily remove 10 or more lines of boilerplate so you spend less time with setup and more time with your tests. Check it out.\n\nThe [bardjs repo](https://github.com/wardbell/bardjs/snippets/ \"bard code snippets\") also contains code snippets to make writing tests a little easier. See [separate instructions](#snippets) for those below.\n\n# Installation\n\nMost folks bardjs install it with [bower](http://bower.io/search/?q=bardjs \"bard on bower\") or [npm](https://www.npmjs.com/package/bardjs):\n\n`bower install bardjs`\n\n`npm install bardjs`\n\nYou can also clone [bardjs from github](https://github.com/wardbell/bardjs \"bard on github\") and extract *bard.js*itself.\n\n>bard depends on [sinon.js](http://sinonjs.org/) so make sure you have that library available; bower and npm bring that down for you.\n\nAlmost all of bard is in the *bard.js* file within the *dist* folder.\n\nIf you're running tests in a browser, add the appropriate script tag *below* the script for your test framework library:\n\n    <!-- when installed with bower -->\n    <script src=\"/bower_components/bardjs/dist/bard.js\"></script>\n\n    <!-- when installed with npm -->\n    <script src=\"/npm_modules/bardjs/dist/bard.js\"></script>\n\nYou'll need to add *sinon.js* as well\n\n    <!-- when installed with bower -->\n    <script src=\"/bower_components/sinon/index.js\"></script>\n\n    <!-- when installed with npm -->\n    <script src=\"/npm_modules/sinon/lib/sinon.js\"></script>\n\n## karma considerations\n\nIf you're running with [karma](http://karma-runner.github.io/0.12/index.html \"karma\"), reference *bard.js* in *karma.config.js* among the `files` to be loaded. See the [karma \"Config\" documentation](http://karma-runner.github.io/0.12/config/configuration-file.html \"karma config\") for details.\n\nBe sure to include *sinon* among the karma frameworks as in this example extract:\n\n    frameworks: ['mocha', 'chai', 'sinon', 'chai-sinon'],\n\nIn the *dist* folder you'll also find optional plug-in extensions such as the *bard-ngRouteTester.js* which adds the `bard.ngRouteTester` helper to manage tests of the [original Angular router](https://docs.angularjs.org/api/ngRoute/service/$route \"Angular $route\"). \n\n# bard methods\n\nAfter loading `bard.js`, you'll find the global variable `bard` at your finger tips as you write your tests. \n\nThe bard methods are listed right at the top of the *bard.js* file. \n\nWe won't describe every method here. Each method is prefaced in the code with it own documentation in comments describing both purpose and usage.\n\nBut we will call out the methods that have proven most notable and useful:\n\n* [appModule](#appModule) - identify the application module to test and also disable certain routine services.\n* [asyncModule](#asyncModule) - enable async integration testing by restoring `$http` and `$q` while identifying the application module to test.\n* [inject](#inject) - inject angular and application components and store them by name on the global `window` object.\n* [fake services](#fakeServices) - register disabled services that you can spy on.\n* [log](#log) - writes messages to `console` when bard debugging is turned on.\n* [mockService](#mockService) - create a mock for any service with spies and return values for every service member.\n\n\n<a name=\"appModule\"></a>\n## appModule\n\n**Identify the application module to test and also disable certain routine services.**\n\nYou typically identify the application module that defines the component you want to test and its dependent services at the top of a test suite. You do this with the [`angular.mock.module` function](https://docs.angularjs.org/api/ngMock/function/angular.mock.module \"mock module\").\n\nWe found that we routinely disable certain services at the same time. \n\nFor example, we don't want to see [**toastr**](https://github.com/CodeSeven/toastr \"toastr\") messages in our browser while our tests are running. We may need to assert that `toastr` was called in  a particular way but we'd prefer to hide the toasts themselves.\n\nWe also discovered that routing services can fire when the app module loads and trigger failures that have nothing to do with the subject of our tests. We just want routing to go away.\n\nThe bard `appModule` method is a quick way to both identify the module to test and disable the *toastr* and routing services. This one line ...\n\n`beforeEach(bard.appModule('myModule'));`\n\ndoes the work of these seven ...\n\n    beforeEach(angular.mock.module(\n\t\t'myModule',\n\t\tbard.fakeToastr,\n\t\tbard.fakeRouteHelperProvider,\n\t\tbard.fakeRouteProvider,\n\t\tbard.fakeStateProvider)\n    );\n\n>The bard library offers [several methods](#fakeServices) (all beginning with the word \"fake\") that each disable a particular service. Don't worry if you haven't included all or any of these services in your app. Registering them will be harmless. Not using *toastr*? Not using the *UIRouter*? No problem.\n\nLike the [`angular.mock.module` function](https://docs.angularjs.org/api/ngMock/function/angular.mock.module \"mock module\"), you can add configuration arguments to the call to decorate or mock other services:\n\n`beforeEach(bard.appModule('myModule', someDecorator, someMock));`\n\n### don't use *appModule* when testing routes\n\nYou can't use `bard.appModule` and test the router. For example, if you want to know that a controller would route the user to a particular view, you can't use `bard.appModule`. There is no way to \"unfake\" the router service once it's been faked.\n\nInstead, simply fall back to `angular.mock.module`, adding specific fakes as desired:\n\n`beforeEach(module('myModule', bard.fakeToastr));`\n\n<a name=\"asyncModule\"></a>\n## asyncModule\n\n**Enable async integration testing by restoring `$httpBackend` and `$q` while identifying the application module to test.**\n\nThe [`angular.mock.module` function](https://docs.angularjs.org/api/ngMock/function/angular.mock.module \"mock module\") replaces  `$httpBackend` and `$q` with mocked versions.\n\nThe mocked `$httpBackend` prevents `$http` from issuing the AJAX calls necessary to communicate with a remote service. The mocked `$q` requires a manual digest cycle to \"flush\" the promise queue and prevents event-driven promise fulfillment.\n\nThese mocks are great for testing *asynchronous* behaviors with fast *synchronous* tests. But you can't write integration tests that require interactions with a server while these mocks are in play. \n\nFor example, you can't test that a `dataservice` works as expected when it sends requests to the remote data server. You can simulate how you *think* that server will respond. But what if the real server behaves differently than your simulation? How can you confirm that your `dataservice` continues working even after changes to the backend that you don't even know about?\n\nYou'll want at least a few cross-process, ***truly asynchronous integration tests*** for peace of mind. You can't have them while `$httpBackend` and `$q` are mocked.\n\nThe bard `asyncModule` method restores the original `$httpBackend` and `$q` at the same time that you identify the application module under test. Here's how you might call it:\n\n`beforeEach(bard.asyncModule('app'));`\n\nThis is the equivalent of ...\n\n    beforeEach(module('app', bard.$httpBackendReal, bard.$qReal, bard.fakeToastr));\n\n>The bard library's `$httpBackendReal` and `$qReal` restore the original angular `$httpBackend` and `$q` implementations; they may be invoked independently.\n>\n>We're also faking *toastr* for the same reason we faked it in [`appModule`](#appModule).\n\nNow you write asynchronous tests that look a lot like production code. Here's a mocha example:\n\n    it('should get at least 6 Avengers', function (done) {\n        dataservice\n            .getAvengers()\n            .then(function(data) {\n                expect(data).to.have.length.above(6);\n            })\n            .then(done, done);\n    });\n\nYou should see network traffic for the request and response to the  \"Avengers\" query. The promise succeeds (or fails) in real time, without stimulus from `$rootScope.$apply()`. The test framework pauses and waits until the server responds (or timesout) and the final `then` invokes the test harness' `done` function. Only then will it proceed to the next test in the suite.\n\nLike the [`angular.mock.module` function](https://docs.angularjs.org/api/ngMock/function/angular.mock.module \"mock module\"), you can add configuration arguments to decorate or mock other services:\n\n`beforeEach(bard.asyncModule('app', someDecorator, someMock));`\n\n\n\n<a name=\"inject\"></a>\n## inject\n\n**Inject angular and application components and store them by name on the global `window` object.**\n\nThe `bard.inject` method tells the Angular [mock dependency injector](https://docs.angularjs.org/api/ngMock/function/angular.mock.inject \"mock inject\") to inject components for the currently active test.\n\nHere's how you might use `inject` within a `beforeEach` to get five dependent services while testing an Angular controller:\n\n    bard.inject(this, '$controller', '$log', '$q', '$rootScope', 'dataservice');\n\nNow you can refer to these services by name in subsequent test functions as in these examples:\n\n    var controller = $controller('Avengers');\n    sinon.stub(dataservice, 'getAvengers').returns($q.when(avengers));\n    $rootScope.$apply();\n    expect(dataservice.getAvengers).to.have.been.calledOnce;\n    expect($log.error.logs[0]).to.match(/doomed/);\n\nCompare the simplicity of \n\n    bard.inject(this, '$controller', '$log', '$q', '$rootScope', 'dataservice');\n\nto the typical approach without bard:\n\n    // declare local variables for use within subsequent test functions\n    var $controller, $log, $q, $rootScope, dataservice;\n\n    // inject the services using Angular \"underscore wrapping\"\n    beforeEach(inject(function(_$controller_, _$log_, _$q_, _$rootScope_, _dataservice_) {\n        // wire local vars to the injected services\n        $controller = _$controller_;\n        $log = _$log_;\n        $q = _$q_;\n        $rootScope = _$rootScope_;\n        dataservice = _dataservice_;\n    }));\n\nWhich would you rather write? As importantly, which would you rather *read* ... on your way to the important business of the tests themselves?\n\n### \"but globals are bad\"\n\nIt's a terrible idea to toss variables into the global namespace *in production*. \n\nIt's tactically smart, productive, and convenient to do so *in your tests*. Disagree? Do you write your test code with `beforeEach`, `it`, `expect`, and `module`? Or would you rather write with the annoyingly verbose equivalents: `mocha.beforeEach`, `jasmine.it`, `chai.expect` and `angular.mock.module`? \n\nthe main risk of globals is ***cross-test pollution***, the risk that the values you set in one test will carry over to a later test. Fortunately, bard `inject` deletes these variables from the global namespace at the end of each test. Each new test gets a clean slate.\n\n### what is `this`?\n\nNotice the *`this`* argument in \n\n<code>bard.inject(</code><strong><code>this</code></strong><code>, '$controller', '$log', '$q', '$rootScope', 'dataservice');</code>\n\nTest frameworks set `this` to the test context (the spec context) object when the test runs. If we pass the context to `inject`, it can tell the test framework to ignore the new injected variables that it adds to the global namespace (the `window` object).\n\nDo you care? You will care if you fear that your application code is leaking variables to the global namespace. You might then configure the test framework to detect such leaks.\n\nFor example, mocha has a \"checkLeaks\" configuration option that you can turn on like so:\n\n    <script>\n        mocha.checkLeaks();\n        var runner = mocha.run();\n    </script>\n\nThus enabled, mocha fails any test that adds variables to the global namespace between the time the test starts and when it finishes.\n\nThat's a problem for `bard.inject` which ***always*** adds new variables to globals. We don't want the tests to fail because of `bard.inject`.\n\nFortunately, `inject` can tell mocha to ignore the injected variables if we give it the spec context via `this`.\n\n>Internally `inject` calls another bard function, `addGlobals`. You should call this too if you deliberately extend globals yourself.\n\n**You don't have to pass `this` to `inject` if you aren't checking for global leaks.** You are free to omit it as in:\n\n    bard.inject('$controller', '$log', '$q', '$rootScope', 'dataservice');\n\nOf course you'll regret the omission later should you decide to turn on mocha's global leak checking. We think it's prudent to include `this` in your call.\n\n### *inject* a function\n\nThe [`angular.mock.inject`](https://docs.angularjs.org/api/ngMock/function/angular.mock.inject \"mock inject\") function can both retrieve injectable \"services\" and do things with them in the function body.\n\nThe bard `inject` method accepts the same kind of function which may be useful if you want to inject and do work at the same time. For example:\n\n    beforeEach(bard.inject(function($controller, $log, $q, $rootScope, dataservice) { \n        ... do work ..\n    }));\n\nAfter the function completes, bard `inject` promotes the injected services to global variables.\n\n\n\n<a name=\"fakeServices\"></a>\n## fake services\n\n**Register disabled services that you can spy on.**\n\nOur applications often depend on certain specific services that we like to disable during most of our tests.\n\nBard offers fake versions of these services. Their methods names begin with the word \"fake\" and include:\n\n    fakeLogger\n    fakeRouteHelperProvider\n    fakeRouteProvider\n    fakeStateProvider\n    fakeToastr\n\nLook for details in *bard.js*. They all have two features in common:\n\n1. they do nothing\n1. their function members are stubbed with [sinon spies](http://sinonjs.org/docs/#spies \"sinon spies\")\n\nThe spies allow a test to assert that one of the service methods was called in the expected manner.\n\n`expect(toastr.error).to.have.been.calledWith('uh oh!');`\n\nYou typically register these faked services by including them among the arguments to the [`angular.mock.module` function](https://docs.angularjs.org/api/ngMock/function/angular.mock.module \"mock module\") or one of its bard substitutes:\n\n    beforeEach(module('myMod', bard.fakeLogger));\n    beforeEach(appModule('myMod', bard.fakeLogger));\n    beforeEach(asyncModule('myMod', bard.fakeLogger));\n\n\n\n<a name=\"log\"></a>\n## log\n\n**The bard `log` method writes messages to `console` when bard debugging is turned on.**\n\nOur tests generally don't write to the console because the console is usually hidden when running tests in the browser or is crowded with other messages when running in karma.\n\nBut it can be helpful to sprinkle a little console logging in our code when trying to understand and debug complex tests.\n\n    it('should be good', function() {\n        ... tricky stuff that might not work ...\n        bard.log('we got the goods');    // conditional bard logging\n        ... more tricky stuff ...\n        expect(good).to.match(/good/);\n    });\n\nWe may wish to leave such diagnostic logging behind ... inert for the most part but ready to go again in a future visit. We can turn conditional logging on with `bard.debugging(true)` and off again with `bard.debugging(false)`. When debugging is off, calls to `bard.log` do nothing.\n\nSome of bard's own methods call `bard.log`.\n\n\n\n<a name=\"mockService\"></a>\n## mockService\n\n**Quickly create a mock for any service with spies and return values for every service member.**\n\nIt can be painful to mock a dependency with a large API. Suppose, for example, that our app has a `dataservice` with 30 members. We want to test a particular controller that depends on this service. \n\nThat controller might call *any* of the service methods, either during initialization or when subjected to test conditions. For this round of tests, we only care when it calls the `dataservice.getAvengers` method.\n\nNo matter what the controller does, the `dataservice` must not dispatch requests to a server. It's obviously terrible if the controller calls a missing method and the mock blows up. We'll have to mock every `dataservice` member ... and remember to update it as the `dataservice` evolves.\n\nSuch a mock `dataservice` is tedious to write by hand, especially when we don't care what most of the members do. The bard `mockService` makes writing this fake a lot easier. The entire setup could be as simple as:\n\n    beforeEach(function() {\n\n        bard.appModule('app.avengers');\n        bard.inject(this, '$controller', '$q', '$rootScope', 'dataservice');\n\n\n        bard.mockService(dataservice, {\n            getAvengers: $q.when(avengers),\n            _default:    $q.when([])\n        });\n\n\n        controller = $controller('Avengers');\n        $rootScope.$apply();\n    });\n\nThe details of `mockService` configuration are described in *bard.js*. You'll find  usage examples in the test coverage (look for *~/tests/bard.mockService.spec.js*). \n\nWe trust you can see the core ideas in this example:\n\n* you give `mockService` an instance of the real `dataservice` to act as a template.\n* the `mockService` replaces every `dataservice` member with a fake implementation.\n* all methods are stubbed with [sinon spies](http://sinonjs.org/docs/#spies \"sinon spies\").\n* you can supply return values (such as fulfilled promises) for *specific* methods.\n* you determine default return values for the remaining *unspecified* methods.\n\nIn this case, we arranged for the `getAvengers` method to return a resolved promise with fake \"avenger\" objects. The other 29 methods return a resolved promise with an empty array.\n\nThat's easier to write and read than a mock `dataservice` with thirty hand-coded stub methods.\n\nAnd here are two mocha/chai tests that could follow that setup:\n\n    it('controller activation gets avengers', function() {\n        controller.activate(); // calls `dataservice.getAvengers`\n        $rootScope.$apply();   // flush pending promises\n            \n        expect(controller.avengers).to.have.length(avengers.length); // same number as mocked\n\n        expect(dataservice.getAvengers).to.have.been.calledOnce; // it's a spy\n    });\n\n    // Call one of the default mock methods which should return \n    // a promise resolving to an empty array\n    // Note that the controller would not have called this on its own\n    it('can call fake `dataservice.getNews`', function() {\n\n        dataservice.getNews().then(function(news) {\n            expect(news).to.have.length(0);\n        });\n\n        $rootScope.$apply(); // flush pending promises\n\n        // verify that `getNews` is actually a spy\n        expect(dataservice.getNews).to.have.been.calledOnce;\n    });\n\n<a name=\"snippets\"></a>\n# Brackets code snippets\n\nCode snippets make test authoring just a little easier. Here\nare instructions for loading our snippets into the [Brackets editor](http://brackets.io/ \"Brackets editor\").\n\n- Open the Brackets Extension manager ( File > Extension manager )\n- Install ['Brackets Snippets (by edc)'](https://github.com/chuyik/brackets-snippets)\n- Click the light bulb in Brackets' right gutter\n- Click `Settings` and then `Import`\n- Click `Choose File`\n- Locate and download [*~/snippets/brackets-testing-snippets.yaml*](https://github.com/wardbell/bardjs/blob/master/snippets/brackets-testing-snippets.yaml \"bard brackets snippets on github\") from github.\n- Choose either to `skip` or to `override`\n- Click `Start Import`\n\nNow try them in a JavaScript test file\n\n* mocha/jasmine\n\n    * `bdescribe` - mocha/jasmine `describe`\n    * `bit`  - `it` test (synchronous)\n    * `bait` - async `it` test\n    * `bbeforeEach` - mocha/jasmine `beforeEach`\n    * `bafterEach` - mocha/jasmine `afterEach`\n    * `bdone` - tail of a mocha test promise chain: `.then(done, done);`\n\n\n* chai expectations\n\n    * `bexpect` - expect(...).to\n    * `bcalled` - expect(...).to.have.been.called\n    * `bequal` - expect(...).to.equal(...)\n    * `blen` - expect(...).to.have.length(...)\n    * `bmatch` - expect(...).to.match(/.../i)\n    * `bprop` - expect(...).to.have.been.property(..., ...)\n    * `bthrow` - expect function to throw\n\n\n* bard.js\n\n    * `binject` - bard.inject\n    * `bcinject` - bard.inject for a controller\n    * `bmodule` - bard.appModule\n    * `basyncmod` - bard.asyncModule\n    * `bverify` - bard.verifyNoOutstandingHttpRequests()\n\n\n* angular.js\n\n    * `bapply` - $rootScope.$apply();\n    * `bwhen`  - $httpBackend.when('get', {url}).respond({status}, {data});\n    * `bflush` - $httpBackend.flush();\n\n* miscellaneous\n\n    * `bfn`    - generates a function stub\n"
  },
  {
    "path": "bard-ngRouteTester.js",
    "content": "/* jshint -W117, -W030 */\n(function() {\n    window.bard = window.bard || {};\n    /**\n     * Creates the global ngRouteTester function\n     * to help test ngRoute changes in the DOM\n     *\n     * Usage:\n     *\n     *     beforeEach(function() {\n     *        module('app.module', ngRouteTester(options));\n     *        ... other config ...\n     *        ... ready to roll; inject! ...\n     *        bard.inject('ngRouteTester', ...);\n     *     });\n     *\n     * @function ngRouteTester\n     * @param {Object} [opts]\n     * @param {Object} [opts.document=document] The document node of the page\n     * @param {Object} [opts.templateUrl] The template file for the HTML layout of the tester\n     * @param {Object} [opts.template] The template string for the HTML layout of the tester\n     * @param {Object} [opts.mockLocationPaths=true] Whether or not to fake the URL change in the browser address bar\n     *\n     * Thanks to Matias Niemelä and his ngMidwayTester from\n     * which most of this code is lifted.\n     * See http://www.yearofmoo.com/2013/01/full-spectrum-testing-with-angularjs-and-karma.html\n     */\n    window.bard.ngRouteTester = function(opts) {\n\n        ngRouteTester.$inject = ['$provide'];\n\n        return ngRouteTester;\n        ///////////////////\n\n        function ngRouteTester($provide) {\n            var options = {\n                document: document\n            };\n\n            angular.extend(options, opts);\n            configure();\n\n            $provide.factory('ngRouteTester', tester);\n\n            ///////////////////////\n            var $rootElement,\n                $timers = [],\n                $viewContainer,\n                $terminalElement,\n                $viewCounter = 0,\n                doc,\n                noop = angular.noop;\n\n            var viewSelector = 'ng-view, [ng-view], .ng-view, [x-ng-view], [data-ng-view]';\n\n            function configure() {\n\n                doc = options.document;\n\n                $rootElement = angular.element(doc.createElement('div'));\n                $provide.value('$rootElement', $rootElement);\n\n                var mockPaths = options.mockLocationPaths;\n                if (mockPaths == null ? true : mockPaths) {\n                    $provide.decorator('$location', LocationDecorator);\n                }\n\n                if (options.templateUrl) { getTemplate(); }\n\n                if (options.template) {\n                    $rootElement.html(options.template);\n                    var view = angular.element($rootElement[0].querySelector(viewSelector));\n                    $viewContainer = view.parent();\n                } else {\n                    $viewContainer = angular.element('<div><div ng-view></div></div>');\n                    $rootElement.append($viewContainer);\n                }\n            }\n\n            LocationDecorator.$inject = ['$delegate', '$rootScope'];\n\n            function LocationDecorator($delegate, $rootScope) {\n                var _path = $delegate.path();\n                $delegate.path = function(path) {\n                    if (path) {\n                        // sometimes the broadcast triggers a new request for same path\n                        // added this conditional to mitigate risk of this infinite loop\n                        if (_path !== path) {\n                            _path = path;\n                            $rootScope.$broadcast('$locationChangeSuccess', path);\n                        }\n                        return this;\n                    } else {\n                        return _path;\n                    }\n                };\n                return $delegate;\n            }\n\n            // get the template from the server synchronously\n            function getTemplate() {\n                var request = new XMLHttpRequest();\n                request.open('GET', options.templateUrl, false);\n                request.send(null);\n\n                if (request.status !== 200) {\n                    throw new Error('ngRouteTester: Unable to download template file');\n                }\n\n                options.template = request.responseText;\n            }\n\n            // ngRouteTester factory\n            tester.$inject = ['$compile', '$injector', '$rootScope', '$route'];\n\n            function tester($compile, $injector, $rootScope, $route) {\n\n                bootstrap();\n\n                // Arrange for mocha/jasmine to destroy after each test\n                afterEach && afterEach(destroy);\n\n                return {\n                    $injector: $injector,\n                    $rootScope: $rootScope,\n                    $route: $route,\n                    path: path,\n                    rootElement: $rootElement,\n                    until: until,\n                    viewElement : viewElement,\n                    visit : visit\n                };\n                ///////////////////\n\n                function bootstrap() {\n                    $terminalElement = angular.element(\n                        '<div status=\"{{__VIEW_STATUS}}\"></div>');\n\n                    $rootElement.append($terminalElement);\n                    $rootScope.$apply(function() {\n                        $rootElement.data('$injector', $injector);\n                        $compile($rootElement)($rootScope);\n                        angular.element(doc.body).append($rootElement);\n                    });\n                }\n\n                /**\n                 * Removes the $rootElement and clears the module from the page.\n                 * This is done automatically for mocha tests\n                 *\n                 * @method destroy\n                 */\n                function destroy() {\n                    angular.forEach($timers, function(timer) {\n                        clearTimeout(timer);\n                    });\n\n                    var body = angular.element(document.body);\n                    body.removeData();\n                    $rootElement.remove();\n                    $rootScope.$destroy();\n                }\n\n                /**\n                 * @method path\n                 * @return {String} Returns the path of the current route\n                 */\n                function path() {\n                    return $injector.get('$location').path();\n                }\n\n                /**\n                 * @method viewElement\n                 * @return {Element} The current element that has ng-view attached to it\n                 */\n                function viewElement() {\n                    return angular.element($viewContainer[0].querySelector(viewSelector));\n                }\n\n                /**\n                 * Changes the current route of the page and then fires the callback when the page has loaded\n                 *\n                 * @param {String} path The given path that the current route will be changed to\n                 * @param {function} [callback] The given callback to fire once the view has been fully loaded\n                 * @method visit\n                 */\n                function visit(path, callback) {\n\n                    // wait until view shows up\n                    /* jshint -W106 */\n                    $rootScope.__VIEW_STATUS = ++$viewCounter;\n                    /* jshint +W106 */\n                    until(function() {\n                        return parseInt($terminalElement.attr('status')) >= $viewCounter;\n                    }, function() {\n                        // give it another tick to settle\n                        setTimeout(callback || noop, 0);\n                    });\n\n                    // tell router to visit the view\n                    var fn = function() {\n                        $injector.get('$location').path(path);\n                    };\n                    $rootScope.$$phase ? fn() : $rootScope.$apply(fn);\n                }\n\n                /**\n                 * Keeps checking an expression until it returns a truthy value and then runs the provided callback\n                 *\n                 * @param {function} exp The given function to poll\n                 * @param {function} callback The given callback to fire once the exp function returns a truthy value\n                 * @method until\n                 */\n                function until(exp, callback) {\n                    var timer, delay = 50;\n                    timer = setInterval(function() {\n                        if (exp()) {\n                            clearTimeout(timer);\n                            callback();\n                        }\n                    }, delay);\n                    $timers.push(timer);\n                }\n            }\n        }\n    };\n\n})();\n"
  },
  {
    "path": "bard.js",
    "content": "/*jshint -W079, -W117 */\n(function() {\n\n    var bard = {\n        $httpBackend: $httpBackendReal,\n        $q: $qReal,\n        addGlobals: addGlobals,\n        appModule: appModule,\n        assertFail: assertFail,\n        asyncModule: asyncModule,\n        debugging: bardDebugging,\n        fakeLogger: fakeLogger,\n        fakeRouteHelperProvider: fakeRouteHelperProvider,\n        fakeRouteProvider: fakeRouteProvider,\n        fakeStateProvider: fakeStateProvider,\n        fakeToastr: fakeToastr,\n        inject: bardInject,\n        log: bardLog,\n        mochaRunnerListener: mochaRunnerListener,\n        mockService: mockService,\n        replaceAccentChars: replaceAccentChars,\n        verifyNoOutstandingHttpRequests: verifyNoOutstandingHttpRequests,\n        wrapWithDone: wrapWithDone\n    };\n\n    var global = (function() { return this; })();\n\n    // mocha/jasmine/QUnit fns\n    var afterEach = global.afterEach || global.teardown;\n    var beforeEach = global.beforeEach || global.setup;\n\n    var clearInject = [];\n    var currentSpec = null;\n    var debugging = false;\n    var logCounter = 0;\n    var okGlobals = [];\n\n    addBindPolyfill();\n\n    beforeEach(function bardTopBeforeEach() {\n        currentSpec = this;\n    });\n\n    afterEach(function bardTopAfterEach() {\n        currentSpec = null;\n        bard.log('clearing injected globals: ' + clearInject);\n        angular.forEach(clearInject, function(name) {\n            delete global[name];\n        });\n        clearInject.length = 0;\n        okGlobals.length = 0;\n    });\n\n    global.bard = angular.extend(global.bard || {}, bard);\n\n    ////////////////////////\n\n    /*jshint -W101 */\n    /**\n     *  Replaces the ngMock'ed $httpBackend with the real one from ng thus\n     *  restoring the ability to issue AJAX calls to the backend with $http.\n     *\n     *  Note that $q remains ngMocked so you must flush $http calls ($rootScope.$digest).\n     *  Use $rootScope.$apply() for this purpose.\n     *\n     *  Could restore $q with $qReal in which case don't need to flush.\n     *\n     *  Inspired by this StackOverflow answer:\n     *    http://stackoverflow.com/questions/20864764/e2e-mock-httpbackend-doesnt-actually-passthrough-for-me/26992327?iemail=1&noredirect=1#26992327\n     *\n     *  Usage:\n     *\n     *    var myService;\n     *\n     *    beforeEach(module(bard.$httpBackend, 'app');\n     *\n     *    beforeEach(inject(function(_myService_) {\n     *        myService = _myService_;\n     *    }));\n     *\n     *    it('should return valid data', function(done) {\n     *        myService.remoteCall()\n     *            .then(function(data) {\n     *                expect(data).toBeDefined();\n     *            })\n     *            .then(done, done);\n     *\n     *        // because not using $qReal, must flush the $http and $q queues\n     *        $rootScope.$apply;\n     *    });\n     */\n    /*jshint +W101 */\n    function $httpBackendReal($provide) {\n        $provide.provider('$httpBackend', function() {\n            /*jshint validthis:true */\n            this.$get = function() {\n                return angular.injector(['ng']).get('$httpBackend');\n            };\n        });\n    }\n\n    /**\n     *  Replaces the ngMock'ed $q with the real one from ng thus\n     *  obviating the need to flush $http and $q queues\n     *  at the expense of ability to control $q timing.\n     *\n     *  Usage:\n     *\n     *    var myService;\n     *\n     *    // Consider: beforeEach(bard.asyncModule('app'));\n     *\n     *    beforeEach(module(bard.$q, bard.$httpBackend, 'app');\n     *\n     *    beforeEach(inject(function(_myService_) {\n     *        myService = _myService_;\n     *    }));\n     *\n     *    it('should return valid data', function(done) {\n     *        myService.remoteCall()\n     *            .then(function(data) {\n     *                expect(data).toBeDefined();\n     *            })\n     *            .then(done, done);\n     *\n     *        // not need to flush\n     *    });\n     */\n    function $qReal($provide) {\n        $provide.provider('$q', function() {\n            /*jshint validthis:true */\n            this.$get = function() {\n                return angular.injector(['ng']).get('$q');\n            };\n        });\n    }\n    /**\n     * Add names of globals to list of OK globals for this mocha spec\n     * NB: Call this method ONLY if you're using mocha!\n     * NB: Turn off browser-sync else mocha detects the browser-sync globals\n     * like ` ___browserSync___`\n     *\n     * usage:\n     *    addGlobals(this, 'foo');        // where `this` is the spec context\n     *    addGlobals(this, 'foo', bar);\n     *    addGlobals.bind(this)('foo', 'bar');\n     *    addGlobals(ctx, ['foo', 'bar']) // where ctx is the spec context\n     */\n    function addGlobals() {\n        var args = Array.prototype.slice.call(arguments);\n        var ctx = getCtxFromArgs.bind(this)(args);\n        var globs = angular.isArray(args[0]) ? args[0] : args;\n        angular.forEach(globs, function(g) {\n            if (okGlobals.indexOf(g) === -1) {\n                okGlobals.push(g);\n            }\n        });\n        // if a mocha test, add the ok globals to it\n        ctx && ctx.test && ctx.test.globals && ctx.test.globals(okGlobals);\n    }\n\n    /**\n     * Prepare ngMocked application feature module\n     * along with faked toastr, routehelper,\n     * and faked router services.\n     * Especially useful for controller testing\n     * Use it as you would the ngMocks#module method\n     *\n     * DO NOT USE IF YOU NEED THE REAL ROUTER SERVICES!\n     * Fall back to `angular.mock.module(...)` or just `module(...)`\n     *\n     * Useage:\n     *     beforeEach(bard.appModule('app.avengers'));\n     *\n     *     Equivalent to:\n     *       beforeEach(angular.mock.module(\n     *          'app.avengers',\n     *          bard.fakeToastr,\n     *          bard.fakeRouteHelperProvider,\n     *          bard.fakeRouteProvider,\n     *          bard.fakeStateProvider)\n     *       );\n     */\n    function appModule() {\n        var args = Array.prototype.slice.call(arguments, 0);\n        args = args.concat(fakeRouteHelperProvider, fakeRouteProvider,\n                           fakeStateProvider, fakeToastr);\n        return angular.mock.module.apply(angular.mock, args);\n    }\n\n    /**\n     * Assert a failure in mocha, without condition\n     *\n     *  Useage:\n     *     assertFail('you are hosed')\n     *\n     *     Responds:\n     *       AssertionError: you are hosed\n     *       at Object.assertFail (..../test/lib/bard.js:153:15)\n     *       at Context.<anonymous> (.../....spec.js:329:15)\n     *\n     *  OR JUST THROW the chai.AssertionError  and treat this\n     *  as a reminder of how to do it.\n     */\n    function assertFail(message) {\n        throw new chai.AssertionError(message);\n    }\n\n    /**\n     * Prepare ngMocked module definition that makes real $http and $q calls\n     * Also adds fakeLogger to the end of the definition\n     * Use it as you would the ngMocks#module method\n     *\n     *  Useage:\n     *     beforeEach(bard.asyncModule('app'));\n     *\n     *     Equivalent to:\n     *       beforeEach(module('app', bard.$httpBackend, bard.$q, bard.fakeToastr));\n     */\n    function asyncModule() {\n        var args = Array.prototype.slice.call(arguments, 0);\n        args = args.concat($httpBackendReal, $qReal, fakeToastr);\n        // build and return the ngMocked test module\n        return angular.mock.module.apply(angular.mock, args);\n    }\n\n    /**\n     * get/set bard debugging flag\n     */\n    function bardDebugging(x) {\n        if (typeof x !== 'undefined') { debugging = !!x; }\n        return debugging;\n    }\n\n    /**\n     * Write to console if bard debugging flag is on\n     */\n    function bardLog(msg) {\n        if (debugging) {\n            console.log('---bard (' + (logCounter += 1) + ') ' + msg);\n        }\n    }\n\n    /**\n     * inject selected services into the windows object during test\n     * then remove them when test ends with an `afterEach`.\n     *\n     * spares us the repetition of creating common service vars and injecting them\n     *\n     * Option: the first argument may be the mocha spec context object (`this`)\n     *         It MUST be `this` if you what to check for mocha global leaks.\n     *         Do NOT supply `this` as the first arg if you're not running mocha specs.\n     *\n     * remaining inject arguments may take one of 3 forms :\n     *\n     *    function    - This fn will be passed to ngMocks.inject.\n     *                  Annotations extracted after inject does its thing.\n     *    [strings]   - same string array you'd use to set fn.$inject\n     *    (...string) - string arguments turned into a string array\n\n     *\n     * usage:\n     *\n     *    bard.inject(this, ...); // `this` === the spec context\n     *\n     *    bard.inject(this, '$log', 'dataservice');\n     *    bard.inject(this, ['$log', 'dataservice']);\n     *    bard.inject(this, function($log, dataservice) { ... });\n     *\n     */\n    function bardInject () {\n        var args = Array.prototype.slice.call(arguments);\n        var ctx = getCtxFromArgs.bind(this)(args);\n        var first = args[0];\n\n        if (typeof first === 'function') {\n            // use ngMocks.inject to execute the func in the arg\n            angular.mock.inject(first);\n            args = first.$inject;\n            if (!args) {\n                // unfortunately ngMocks.inject only prepares inject.$inject for us\n                // if using strictDi as of v.1.3.8\n                // therefore, apply its annotation extraction logic manually\n                args = getinjectargs(first);\n            }\n        }\n        else if (angular.isArray(first)) {\n            args = first; // assume is an array of strings\n        }\n        // else assume all args are strings\n\n        var $injector = currentSpec.$injector;\n        if (!$injector) {\n            angular.mock.inject(); // create the injector\n            $injector = currentSpec.$injector;\n        }\n\n        var names = [];\n        angular.forEach(args, function(name, ix) {\n\n            if (typeof name !== 'string') {\n                return; // WAT? Only strings allowed. Let's skip it and move on.\n            }\n            var value = $injector.get(name);\n            if (value == null) { return; }\n\n            var pathName = name.split('.');\n\n            if (pathName.length > 1) {\n                // name is a path like 'block.foo'. Can't use as identifier\n                // assume last segment should be identifier name, e.g. 'foo'\n                name = pathName[pathName.length - 1];\n                // todo: tolerate component names that are invalid JS identifiers, e.g. 'burning man'\n            }\n            global[name] = value;\n            clearInject.push(name);\n            names.push(name);\n        });\n\n        bard.addGlobals.bind(ctx)(names);\n    }\n\n    function fakeLogger($provide) {\n        $provide.value('logger', sinon.stub({\n            info: function() {},\n            error: function() {},\n            warning: function() {},\n            success: function() {}\n        }));\n    }\n\n    function fakeToastr($provide) {\n        $provide.constant('toastr', sinon.stub({\n            info: function() {},\n            error: function() {},\n            warning: function() {},\n            success: function() {}\n        }));\n    }\n\n    function fakeRouteHelperProvider($provide) {\n        $provide.provider('routehelper', function() {\n            /* jshint validthis:true */\n            this.config = {\n                $routeProvider: undefined,\n                docTitle: 'Testing'\n            };\n            this.$get = function() {\n                return {\n                    configureRoutes: sinon.stub(),\n                    getRoutes: sinon.stub().returns([]),\n                    routeCounts: {\n                        errors: 0,\n                        changes: 0\n                    }\n                };\n            };\n        });\n    }\n\n    function fakeRouteProvider($provide) {\n        /**\n         * Stub out the $routeProvider so we avoid\n         * all routing calls, including the default route\n         * which runs on every test otherwise.\n         * Make sure this goes before the inject in the spec.\n         *\n         * Optionally set up the fake behavior in your tests by monkey patching\n         * the faked $route router. For example:\n         *\n         * beforeEach(function() {\n         *      // get fake $route router service\n         *      bard.inject(this, '$route');\n         *\n         *      // plug in fake $route router values for this set of tests\n         *      $route.current = { ... fake values here ... };\n         *      $route.routes  = { ... fake values here ... };\n         *  })\n         */\n        $provide.provider('$route', function() {\n            /* jshint validthis:true */\n            this.when = sinon.stub();\n            this.otherwise = sinon.stub();\n\n            this.$get = function() {\n                return {\n                    // current: {},  // fake before each test as needed\n                    // routes:  {}  // fake before each test as needed\n                    // more? You'll know when it fails :-)\n                    _faked: 'this is the faked $route service'\n                };\n            };\n        });\n    }\n\n    function fakeStateProvider($provide) {\n        /**\n         * Stub out the $stateProvider so we avoid\n         * all routing calls, including the default state\n         * which runs on every test otherwise.\n         * Make sure this goes before the inject in the spec.\n         *\n         * Optionally set up the fake behavior in your tests by monkey patching\n         * the faked $state router. For example:\n         *\n         * beforeEach(function() {\n         *      // get fake $state router service\n         *      bard.inject(this, '$state');\n         *\n         *      // plug in fake $state router values for this set of tests\n         *      $state.current = { ... fake values here ... };\n         *      $state.state   = { ... fake values here ... };\n         *  })\n         */\n        $provide.provider('$state', function() {\n            /* jshint validthis:true */\n            this.state = sinon.stub();\n\n            this.$get = function() {\n                return {\n                    // current: {},  // fake before each test as needed\n                    // state:  {}  // fake before each test as needed\n                    // more? You'll know when it fails :-)\n                    _faked: 'this is the faked $state service'\n                };\n            };\n        });\n        $provide.provider('$urlRouter', function() {\n            /* jshint validthis:true */\n            this.otherwise = sinon.stub();\n\n            this.$get = function() {\n                return {\n                    // current: {},  // fake before each test as needed\n                    // states:  {}  // fake before each test as needed\n                    // more? You'll know when it fails :-)\n                    _faked: 'this is the faked $urlRouter service'\n                };\n            };\n        });\n    }\n\n    /**\n     * Get the spec context from parameters (if there)\n     * or from `this` (if it is the ctx as a result of `bind`)\n     */\n    function getCtxFromArgs(args) {\n        var ctx;\n        var first = args[0];\n        // heuristic to discover if the first arg is the mocha spec context (`this`)\n        if (first && first.test) {\n            // The first arg was the mocha spec context (`this`)\n            // Get it and strip it from args\n            ctx = args.shift();\n        } else if (this.test) {\n            // alternative: caller can bind bardInject to the spec context\n            ctx = this;\n        }\n        return ctx;\n    }\n\n    /**\n     * Inspired by Angular; that's how they get the parms for injection\n     * Todo: no longer used by `injector`. Remove?\n     */\n    function getFnParams(fn) {\n        var fnText;\n        var argDecl;\n\n        var FN_ARGS = /^function\\s*[^\\(]*\\(\\s*([^\\)]*)\\)/m;\n        var FN_ARG_SPLIT = /,/;\n        var FN_ARG = /^\\s*(_?)(\\S+?)\\1\\s*$/;\n        var STRIP_COMMENTS = /((\\/\\/.*$)|(\\/\\*[\\s\\S]*?\\*\\/))/mg;\n        var params = [];\n        if (fn.length) {\n            fnText = fn.toString().replace(STRIP_COMMENTS, '');\n            argDecl = fnText.match(FN_ARGS);\n            angular.forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {\n                arg.replace(FN_ARG, function(all, underscore, name) {\n                    params.push(name);\n                });\n            });\n        }\n        return params;\n    }\n\n    function isSpecRunning() { return !!currentSpec; }\n\n    /**\n     * Mocks out a service with sinon stubbed functions\n     * that return the values specified in the config\n     *\n     * If the config value is `undefined`,\n     * stub the service method with a dummy that doesn't return a value\n     *\n     * If the config value is a function, set service property with it\n     *\n     * If a service member is a property, not a function,\n     * set it with the config value\n\n     * If a service member name is not a key in config,\n     * follow the same logic as above to set its members\n     * using the config._default value (which is `undefined` if omitted)\n     *\n     * If there is a config entry that is NOT a member of the service\n     * add mocked function to the service using the config value\n     *\n     * Usage:\n     *   Given this DoWork service:\n     *      {\n     *          doWork1:  an async function,\n     *          doWork2:  a function,\n     *          doWork3:  an async function,\n     *          doWork4:  a function,\n     *          isActive: true\n     *      }\n     *\n     *   Given this config:\n     *      {\n     *          doWork1:  $q.when([{name: 'Bob'}, {name: 'Sally'}]),\n     *          doWork2:  undefined,\n     *          //doWork3: not in config therefore will get _default value\n     *          doWork4:  an alternate doWork4 function\n     *          doWork5:  $q.reject('bad boy!')\n     *          isActive: false,\n     *          _default: $q.when([])\n     *      }\n     *\n     *   Service becomes\n     *      {\n     *          doWork1:  a stub returning $q.when([{name: 'Bob'}, {name: 'Sally'}]),\n     *          doWork2:  do-nothing stub,\n     *          doWork3:  a stub returning $q.when([]),\n     *          doWork4:  an alternate doWork4 function,\n     *          doWork5:  a stub returning $q.reject('bad boy!'),\n     *          isActive: false,\n     *      }\n     */\n    function mockService(service, config) {\n\n        var serviceKeys = [];\n        for (var key in service) {\n            serviceKeys.push(key);\n        }\n\n        var configKeys = [];\n        for (var key in config) {\n            configKeys.push(key);\n        }\n\n        angular.forEach(serviceKeys, function(key) {\n            var value = configKeys.indexOf(key) > -1 ?\n                config[key] : config._default;\n\n            if (typeof service[key] === 'function') {\n                if (typeof value === 'function') {\n                    sinon.stub(service, key, value);\n                } else {\n                    sinon.stub(service, key, function() {\n                        return value;\n                    });\n                }\n            } else {\n                service[key] = value;\n            }\n        });\n\n        // for all unused config entries add a sinon stubbed\n        // async method that returns the config value\n        angular.forEach(configKeys, function(key) {\n            if (serviceKeys.indexOf(key) === -1) {\n                var value = config[key];\n                if (typeof value === 'function') {\n                    service[key] = value;\n                } else {\n                    service[key] = sinon.spy(function() {\n                        return value;\n                    });\n                }\n            }\n        });\n\n        return service;\n    }\n\n    /**\n     *  Listen to mocha test runner events\n     *  Usage in browser:\n     *     var runner = mocha.run();\n     *     bard.mochaRunnerListener(runner);\n     */\n    function mochaRunnerListener(runner) {\n        if (!global.mocha) { return; }\n        if (!runner.ignoreLeaks) {\n            runner.on('hook end', addOkGlobals);\n        };\n\n        // When checking global leaks with mocha.checkLeaks()\n        // make sure mocha is aware of bard's okGlobals\n        function addOkGlobals(hook) {\n            // HACK: only way I've found so far to ensure that bard added globals\n            // are always inspected. Using private mocha _allowedGlobals (shhhh!)\n            if (okGlobals.length && !hook._allowedGlobals) {\n                hook._allowedGlobals = okGlobals;\n            }\n        }\n    }\n\n    // Replaces the accented characters of many European languages w/ unaccented chars\n    // Use it in JavaScript string sorts where such characters may be encountered\n    // Matches the default string comparers of most databases.\n    // Ex: replaceAccentChars(a.Name) < replaceAccentChars(b.Name)\n    // instead of:            a.Name  <                    b.Name\n    function replaceAccentChars(s) {\n        var r = s.toLowerCase();\n        r = r.replace(new RegExp(/[àáâãäå]/g), 'a');\n        r = r.replace(new RegExp(/æ/g), 'ae');\n        r = r.replace(new RegExp(/ç/g), 'c');\n        r = r.replace(new RegExp(/[èéêë]/g), 'e');\n        r = r.replace(new RegExp(/[ìíîï]/g), 'i');\n        r = r.replace(new RegExp(/ñ/g), 'n');\n        r = r.replace(new RegExp(/[òóôõö]/g), 'o');\n        r = r.replace(new RegExp(/œ/g), 'oe');\n        r = r.replace(new RegExp(/[ùúûü]/g), 'u');\n        r = r.replace(new RegExp(/[ýÿ]/g), 'y');\n        return r;\n    }\n\n    /**\n     *  Assert that there are no outstanding HTTP requests after test is complete\n     *  For use with ngMocks; doesn't work for async server integration tests\n     */\n    function verifyNoOutstandingHttpRequests () {\n        afterEach(angular.mock.inject(function($httpBackend) {\n            $httpBackend.verifyNoOutstandingExpectation();\n            $httpBackend.verifyNoOutstandingRequest();\n        }));\n    }\n\n    /**\n     * Returns a function that execute a callback function\n     * (typically a fn making asserts) within a try/catch\n     * The try/catch then calls the ambient \"done\" function\n     * in the appropriate way for both success and failure\n     *\n     * Useage:\n     *    bard.inject('ngRouteTester', ...); // see bard-ngRouteTester.js\n     *    ...\n     *    // When the DOM is ready, assert got the dashboard view\n     *    ngRouteTester.until(elemIsReady, wrap(hasDashboardView, done));\n     */\n    function wrapWithDone(callback, done) {\n        return function() {\n            try {\n                callback();\n                done();\n            } catch (err) {\n                done(err);\n            }\n        };\n    }\n\n    /*\n     *  Phantom.js does not support Function.prototype.bind (at least not before v.2.0\n     *  That's just crazy. Everybody supports bind.\n     *  Read about it here: https://groups.google.com/forum/#!msg/phantomjs/r0hPOmnCUpc/uxusqsl2LNoJ\n     *  This polyfill is copied directly from MDN\n     *  https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Compatibility\n     */\n    function addBindPolyfill() {\n        if (Function.prototype.bind) { return; } // already defined\n\n        /*jshint freeze: false */\n        Function.prototype.bind = function (oThis) {\n            if (typeof this !== 'function') {\n                // closest thing possible to the ECMAScript 5\n                // internal IsCallable function\n                throw new TypeError(\n                    'Function.prototype.bind - what is trying to be bound is not callable');\n            }\n\n            var aArgs = Array.prototype.slice.call(arguments, 1),\n                fToBind = this,\n                FuncNoOp = function () {},\n                fBound = function () {\n                    return fToBind.apply(this instanceof FuncNoOp && oThis ? this : oThis,\n                        aArgs.concat(Array.prototype.slice.call(arguments)));\n                };\n\n            FuncNoOp.prototype = this.prototype;\n            fBound.prototype = new FuncNoOp();\n\n            return fBound;\n        };\n    }\n\n})();\n"
  },
  {
    "path": "bower.json",
    "content": "{\n  \"name\": \"bardjs\",\n  \"version\": \"0.1.10\",\n  \"description\": \"Spec helpers for testing angular v.1.x apps with Mocha, Jasmine or QUnit\",\n  \"authors\": [\n    \"John Papa\",\n    \"Ward Bell\"\n  ],\n  \"main\": [\n    \"./dist/bard.js\",\n    \"./dist/bard-ngRouteTester.js\"\n  ],\n  \"license\": \"MIT\",\n  \"homepage\": \"https://github.com/wardbell/bardjs\",\n  \"ignore\": [\n    \"node_modules\",\n    \"bower_components\",\n    \"tests\",\n    \"*.html\",\n    \"*.js\",\n    \".*\"\n  ],\n  \"dependencies\": {\n    \"angular\": \">=1.3.8\",\n    \"angular-mocks\": \">=1.3.8\",\n    \"sinon\": \"~1.15.0\"\n  },\n  \"devDependencies\": {\n    \"chai\": \"^1.9.1\",\n    \"sinon-chai\": \"^2.5.0\"\n  },\n  \"exportsOverride\": {\n    \"sinon\": {\n      \"js\": \"index.js\"\n    }\n  }\n\n}\n"
  },
  {
    "path": "dist/bard-ngRouteTester.js",
    "content": "/**\n * bardjs - Spec helpers for testing angular v.1.x apps with Mocha, Jasmine or QUnit\n * @authors John Papa,Ward Bell\n * @version v0.1.10\n * @link https://github.com/wardbell/bardjs\n * @license MIT\n */\n/* jshint -W117, -W030 */\n(function() {\n    window.bard = window.bard || {};\n    /**\n     * Creates the global ngRouteTester function\n     * to help test ngRoute changes in the DOM\n     *\n     * Usage:\n     *\n     *     beforeEach(function() {\n     *        module('app.module', ngRouteTester(options));\n     *        ... other config ...\n     *        ... ready to roll; inject! ...\n     *        bard.inject('ngRouteTester', ...);\n     *     });\n     *\n     * @function ngRouteTester\n     * @param {Object} [opts]\n     * @param {Object} [opts.document=document] The document node of the page\n     * @param {Object} [opts.templateUrl] The template file for the HTML layout of the tester\n     * @param {Object} [opts.template] The template string for the HTML layout of the tester\n     * @param {Object} [opts.mockLocationPaths=true] Whether or not to fake the URL change in the browser address bar\n     *\n     * Thanks to Matias Niemelä and his ngMidwayTester from\n     * which most of this code is lifted.\n     * See http://www.yearofmoo.com/2013/01/full-spectrum-testing-with-angularjs-and-karma.html\n     */\n    window.bard.ngRouteTester = function(opts) {\n\n        ngRouteTester.$inject = ['$provide'];\n\n        return ngRouteTester;\n        ///////////////////\n\n        function ngRouteTester($provide) {\n            var options = {\n                document: document\n            };\n\n            angular.extend(options, opts);\n            configure();\n\n            $provide.factory('ngRouteTester', tester);\n\n            ///////////////////////\n            var $rootElement,\n                $timers = [],\n                $viewContainer,\n                $terminalElement,\n                $viewCounter = 0,\n                doc,\n                noop = angular.noop;\n\n            var viewSelector = 'ng-view, [ng-view], .ng-view, [x-ng-view], [data-ng-view]';\n\n            function configure() {\n\n                doc = options.document;\n\n                $rootElement = angular.element(doc.createElement('div'));\n                $provide.value('$rootElement', $rootElement);\n\n                var mockPaths = options.mockLocationPaths;\n                if (mockPaths == null ? true : mockPaths) {\n                    $provide.decorator('$location', LocationDecorator);\n                }\n\n                if (options.templateUrl) { getTemplate(); }\n\n                if (options.template) {\n                    $rootElement.html(options.template);\n                    var view = angular.element($rootElement[0].querySelector(viewSelector));\n                    $viewContainer = view.parent();\n                } else {\n                    $viewContainer = angular.element('<div><div ng-view></div></div>');\n                    $rootElement.append($viewContainer);\n                }\n            }\n\n            LocationDecorator.$inject = ['$delegate', '$rootScope'];\n\n            function LocationDecorator($delegate, $rootScope) {\n                var _path = $delegate.path();\n                $delegate.path = function(path) {\n                    if (path) {\n                        // sometimes the broadcast triggers a new request for same path\n                        // added this conditional to mitigate risk of this infinite loop\n                        if (_path !== path) {\n                            _path = path;\n                            $rootScope.$broadcast('$locationChangeSuccess', path);\n                        }\n                        return this;\n                    } else {\n                        return _path;\n                    }\n                };\n                return $delegate;\n            }\n\n            // get the template from the server synchronously\n            function getTemplate() {\n                var request = new XMLHttpRequest();\n                request.open('GET', options.templateUrl, false);\n                request.send(null);\n\n                if (request.status !== 200) {\n                    throw new Error('ngRouteTester: Unable to download template file');\n                }\n\n                options.template = request.responseText;\n            }\n\n            // ngRouteTester factory\n            tester.$inject = ['$compile', '$injector', '$rootScope', '$route'];\n\n            function tester($compile, $injector, $rootScope, $route) {\n\n                bootstrap();\n\n                // Arrange for mocha/jasmine to destroy after each test\n                afterEach && afterEach(destroy);\n\n                return {\n                    $injector: $injector,\n                    $rootScope: $rootScope,\n                    $route: $route,\n                    path: path,\n                    rootElement: $rootElement,\n                    until: until,\n                    viewElement : viewElement,\n                    visit : visit\n                };\n                ///////////////////\n\n                function bootstrap() {\n                    $terminalElement = angular.element(\n                        '<div status=\"{{__VIEW_STATUS}}\"></div>');\n\n                    $rootElement.append($terminalElement);\n                    $rootScope.$apply(function() {\n                        $rootElement.data('$injector', $injector);\n                        $compile($rootElement)($rootScope);\n                        angular.element(doc.body).append($rootElement);\n                    });\n                }\n\n                /**\n                 * Removes the $rootElement and clears the module from the page.\n                 * This is done automatically for mocha tests\n                 *\n                 * @method destroy\n                 */\n                function destroy() {\n                    angular.forEach($timers, function(timer) {\n                        clearTimeout(timer);\n                    });\n\n                    var body = angular.element(document.body);\n                    body.removeData();\n                    $rootElement.remove();\n                    $rootScope.$destroy();\n                }\n\n                /**\n                 * @method path\n                 * @return {String} Returns the path of the current route\n                 */\n                function path() {\n                    return $injector.get('$location').path();\n                }\n\n                /**\n                 * @method viewElement\n                 * @return {Element} The current element that has ng-view attached to it\n                 */\n                function viewElement() {\n                    return angular.element($viewContainer[0].querySelector(viewSelector));\n                }\n\n                /**\n                 * Changes the current route of the page and then fires the callback when the page has loaded\n                 *\n                 * @param {String} path The given path that the current route will be changed to\n                 * @param {function} [callback] The given callback to fire once the view has been fully loaded\n                 * @method visit\n                 */\n                function visit(path, callback) {\n\n                    // wait until view shows up\n                    /* jshint -W106 */\n                    $rootScope.__VIEW_STATUS = ++$viewCounter;\n                    /* jshint +W106 */\n                    until(function() {\n                        return parseInt($terminalElement.attr('status')) >= $viewCounter;\n                    }, function() {\n                        // give it another tick to settle\n                        setTimeout(callback || noop, 0);\n                    });\n\n                    // tell router to visit the view\n                    var fn = function() {\n                        $injector.get('$location').path(path);\n                    };\n                    $rootScope.$$phase ? fn() : $rootScope.$apply(fn);\n                }\n\n                /**\n                 * Keeps checking an expression until it returns a truthy value and then runs the provided callback\n                 *\n                 * @param {function} exp The given function to poll\n                 * @param {function} callback The given callback to fire once the exp function returns a truthy value\n                 * @method until\n                 */\n                function until(exp, callback) {\n                    var timer, delay = 50;\n                    timer = setInterval(function() {\n                        if (exp()) {\n                            clearTimeout(timer);\n                            callback();\n                        }\n                    }, delay);\n                    $timers.push(timer);\n                }\n            }\n        }\n    };\n\n})();\n"
  },
  {
    "path": "dist/bard.js",
    "content": "/**\n * bardjs - Spec helpers for testing angular v.1.x apps with Mocha, Jasmine or QUnit\n * @authors John Papa,Ward Bell\n * @version v0.1.10\n * @link https://github.com/wardbell/bardjs\n * @license MIT\n */\n/*jshint -W079, -W117 */\n(function() {\n\n    var bard = {\n        $httpBackend: $httpBackendReal,\n        $q: $qReal,\n        addGlobals: addGlobals,\n        appModule: appModule,\n        assertFail: assertFail,\n        asyncModule: asyncModule,\n        debugging: bardDebugging,\n        fakeLogger: fakeLogger,\n        fakeRouteHelperProvider: fakeRouteHelperProvider,\n        fakeRouteProvider: fakeRouteProvider,\n        fakeStateProvider: fakeStateProvider,\n        fakeToastr: fakeToastr,\n        inject: bardInject,\n        log: bardLog,\n        mochaRunnerListener: mochaRunnerListener,\n        mockService: mockService,\n        replaceAccentChars: replaceAccentChars,\n        verifyNoOutstandingHttpRequests: verifyNoOutstandingHttpRequests,\n        wrapWithDone: wrapWithDone\n    };\n\n    var global = (function() { return this; })();\n\n    // mocha/jasmine/QUnit fns\n    var afterEach = global.afterEach || global.teardown;\n    var beforeEach = global.beforeEach || global.setup;\n\n    var clearInject = [];\n    var currentSpec = null;\n    var debugging = false;\n    var logCounter = 0;\n    var okGlobals = [];\n\n    addBindPolyfill();\n\n    beforeEach(function bardTopBeforeEach() {\n        currentSpec = this;\n    });\n\n    afterEach(function bardTopAfterEach() {\n        currentSpec = null;\n        bard.log('clearing injected globals: ' + clearInject);\n        angular.forEach(clearInject, function(name) {\n            delete global[name];\n        });\n        clearInject.length = 0;\n        okGlobals.length = 0;\n    });\n\n    global.bard = angular.extend(global.bard || {}, bard);\n\n    ////////////////////////\n\n    /*jshint -W101 */\n    /**\n     *  Replaces the ngMock'ed $httpBackend with the real one from ng thus\n     *  restoring the ability to issue AJAX calls to the backend with $http.\n     *\n     *  Note that $q remains ngMocked so you must flush $http calls ($rootScope.$digest).\n     *  Use $rootScope.$apply() for this purpose.\n     *\n     *  Could restore $q with $qReal in which case don't need to flush.\n     *\n     *  Inspired by this StackOverflow answer:\n     *    http://stackoverflow.com/questions/20864764/e2e-mock-httpbackend-doesnt-actually-passthrough-for-me/26992327?iemail=1&noredirect=1#26992327\n     *\n     *  Usage:\n     *\n     *    var myService;\n     *\n     *    beforeEach(module(bard.$httpBackend, 'app');\n     *\n     *    beforeEach(inject(function(_myService_) {\n     *        myService = _myService_;\n     *    }));\n     *\n     *    it('should return valid data', function(done) {\n     *        myService.remoteCall()\n     *            .then(function(data) {\n     *                expect(data).toBeDefined();\n     *            })\n     *            .then(done, done);\n     *\n     *        // because not using $qReal, must flush the $http and $q queues\n     *        $rootScope.$apply;\n     *    });\n     */\n    /*jshint +W101 */\n    function $httpBackendReal($provide) {\n        $provide.provider('$httpBackend', function() {\n            /*jshint validthis:true */\n            this.$get = function() {\n                return angular.injector(['ng']).get('$httpBackend');\n            };\n        });\n    }\n\n    /**\n     *  Replaces the ngMock'ed $q with the real one from ng thus\n     *  obviating the need to flush $http and $q queues\n     *  at the expense of ability to control $q timing.\n     *\n     *  Usage:\n     *\n     *    var myService;\n     *\n     *    // Consider: beforeEach(bard.asyncModule('app'));\n     *\n     *    beforeEach(module(bard.$q, bard.$httpBackend, 'app');\n     *\n     *    beforeEach(inject(function(_myService_) {\n     *        myService = _myService_;\n     *    }));\n     *\n     *    it('should return valid data', function(done) {\n     *        myService.remoteCall()\n     *            .then(function(data) {\n     *                expect(data).toBeDefined();\n     *            })\n     *            .then(done, done);\n     *\n     *        // not need to flush\n     *    });\n     */\n    function $qReal($provide) {\n        $provide.provider('$q', function() {\n            /*jshint validthis:true */\n            this.$get = function() {\n                return angular.injector(['ng']).get('$q');\n            };\n        });\n    }\n    /**\n     * Add names of globals to list of OK globals for this mocha spec\n     * NB: Call this method ONLY if you're using mocha!\n     * NB: Turn off browser-sync else mocha detects the browser-sync globals\n     * like ` ___browserSync___`\n     *\n     * usage:\n     *    addGlobals(this, 'foo');        // where `this` is the spec context\n     *    addGlobals(this, 'foo', bar);\n     *    addGlobals.bind(this)('foo', 'bar');\n     *    addGlobals(ctx, ['foo', 'bar']) // where ctx is the spec context\n     */\n    function addGlobals() {\n        var args = Array.prototype.slice.call(arguments);\n        var ctx = getCtxFromArgs.bind(this)(args);\n        var globs = angular.isArray(args[0]) ? args[0] : args;\n        angular.forEach(globs, function(g) {\n            if (okGlobals.indexOf(g) === -1) {\n                okGlobals.push(g);\n            }\n        });\n        // if a mocha test, add the ok globals to it\n        ctx && ctx.test && ctx.test.globals && ctx.test.globals(okGlobals);\n    }\n\n    /**\n     * Prepare ngMocked application feature module\n     * along with faked toastr, routehelper,\n     * and faked router services.\n     * Especially useful for controller testing\n     * Use it as you would the ngMocks#module method\n     *\n     * DO NOT USE IF YOU NEED THE REAL ROUTER SERVICES!\n     * Fall back to `angular.mock.module(...)` or just `module(...)`\n     *\n     * Useage:\n     *     beforeEach(bard.appModule('app.avengers'));\n     *\n     *     Equivalent to:\n     *       beforeEach(angular.mock.module(\n     *          'app.avengers',\n     *          bard.fakeToastr,\n     *          bard.fakeRouteHelperProvider,\n     *          bard.fakeRouteProvider,\n     *          bard.fakeStateProvider)\n     *       );\n     */\n    function appModule() {\n        var args = Array.prototype.slice.call(arguments, 0);\n        args = args.concat(fakeRouteHelperProvider, fakeRouteProvider,\n                           fakeStateProvider, fakeToastr);\n        return angular.mock.module.apply(angular.mock, args);\n    }\n\n    /**\n     * Assert a failure in mocha, without condition\n     *\n     *  Useage:\n     *     assertFail('you are hosed')\n     *\n     *     Responds:\n     *       AssertionError: you are hosed\n     *       at Object.assertFail (..../test/lib/bard.js:153:15)\n     *       at Context.<anonymous> (.../....spec.js:329:15)\n     *\n     *  OR JUST THROW the chai.AssertionError  and treat this\n     *  as a reminder of how to do it.\n     */\n    function assertFail(message) {\n        throw new chai.AssertionError(message);\n    }\n\n    /**\n     * Prepare ngMocked module definition that makes real $http and $q calls\n     * Also adds fakeLogger to the end of the definition\n     * Use it as you would the ngMocks#module method\n     *\n     *  Useage:\n     *     beforeEach(bard.asyncModule('app'));\n     *\n     *     Equivalent to:\n     *       beforeEach(module('app', bard.$httpBackend, bard.$q, bard.fakeToastr));\n     */\n    function asyncModule() {\n        var args = Array.prototype.slice.call(arguments, 0);\n        args = args.concat($httpBackendReal, $qReal, fakeToastr);\n        // build and return the ngMocked test module\n        return angular.mock.module.apply(angular.mock, args);\n    }\n\n    /**\n     * get/set bard debugging flag\n     */\n    function bardDebugging(x) {\n        if (typeof x !== 'undefined') { debugging = !!x; }\n        return debugging;\n    }\n\n    /**\n     * Write to console if bard debugging flag is on\n     */\n    function bardLog(msg) {\n        if (debugging) {\n            console.log('---bard (' + (logCounter += 1) + ') ' + msg);\n        }\n    }\n\n    /**\n     * inject selected services into the windows object during test\n     * then remove them when test ends with an `afterEach`.\n     *\n     * spares us the repetition of creating common service vars and injecting them\n     *\n     * Option: the first argument may be the mocha spec context object (`this`)\n     *         It MUST be `this` if you what to check for mocha global leaks.\n     *         Do NOT supply `this` as the first arg if you're not running mocha specs.\n     *\n     * remaining inject arguments may take one of 3 forms :\n     *\n     *    function    - This fn will be passed to ngMocks.inject.\n     *                  Annotations extracted after inject does its thing.\n     *    [strings]   - same string array you'd use to set fn.$inject\n     *    (...string) - string arguments turned into a string array\n\n     *\n     * usage:\n     *\n     *    bard.inject(this, ...); // `this` === the spec context\n     *\n     *    bard.inject(this, '$log', 'dataservice');\n     *    bard.inject(this, ['$log', 'dataservice']);\n     *    bard.inject(this, function($log, dataservice) { ... });\n     *\n     */\n    function bardInject () {\n        var args = Array.prototype.slice.call(arguments);\n        var ctx = getCtxFromArgs.bind(this)(args);\n        var first = args[0];\n\n        if (typeof first === 'function') {\n            // use ngMocks.inject to execute the func in the arg\n            angular.mock.inject(first);\n            args = first.$inject;\n            if (!args) {\n                // unfortunately ngMocks.inject only prepares inject.$inject for us\n                // if using strictDi as of v.1.3.8\n                // therefore, apply its annotation extraction logic manually\n                args = getinjectargs(first);\n            }\n        }\n        else if (angular.isArray(first)) {\n            args = first; // assume is an array of strings\n        }\n        // else assume all args are strings\n\n        var $injector = currentSpec.$injector;\n        if (!$injector) {\n            angular.mock.inject(); // create the injector\n            $injector = currentSpec.$injector;\n        }\n\n        var names = [];\n        angular.forEach(args, function(name, ix) {\n\n            if (typeof name !== 'string') {\n                return; // WAT? Only strings allowed. Let's skip it and move on.\n            }\n            var value = $injector.get(name);\n            if (value == null) { return; }\n\n            var pathName = name.split('.');\n\n            if (pathName.length > 1) {\n                // name is a path like 'block.foo'. Can't use as identifier\n                // assume last segment should be identifier name, e.g. 'foo'\n                name = pathName[pathName.length - 1];\n                // todo: tolerate component names that are invalid JS identifiers, e.g. 'burning man'\n            }\n            global[name] = value;\n            clearInject.push(name);\n            names.push(name);\n        });\n\n        bard.addGlobals.bind(ctx)(names);\n    }\n\n    function fakeLogger($provide) {\n        $provide.value('logger', sinon.stub({\n            info: function() {},\n            error: function() {},\n            warning: function() {},\n            success: function() {}\n        }));\n    }\n\n    function fakeToastr($provide) {\n        $provide.constant('toastr', sinon.stub({\n            info: function() {},\n            error: function() {},\n            warning: function() {},\n            success: function() {}\n        }));\n    }\n\n    function fakeRouteHelperProvider($provide) {\n        $provide.provider('routehelper', function() {\n            /* jshint validthis:true */\n            this.config = {\n                $routeProvider: undefined,\n                docTitle: 'Testing'\n            };\n            this.$get = function() {\n                return {\n                    configureRoutes: sinon.stub(),\n                    getRoutes: sinon.stub().returns([]),\n                    routeCounts: {\n                        errors: 0,\n                        changes: 0\n                    }\n                };\n            };\n        });\n    }\n\n    function fakeRouteProvider($provide) {\n        /**\n         * Stub out the $routeProvider so we avoid\n         * all routing calls, including the default route\n         * which runs on every test otherwise.\n         * Make sure this goes before the inject in the spec.\n         *\n         * Optionally set up the fake behavior in your tests by monkey patching\n         * the faked $route router. For example:\n         *\n         * beforeEach(function() {\n         *      // get fake $route router service\n         *      bard.inject(this, '$route');\n         *\n         *      // plug in fake $route router values for this set of tests\n         *      $route.current = { ... fake values here ... };\n         *      $route.routes  = { ... fake values here ... };\n         *  })\n         */\n        $provide.provider('$route', function() {\n            /* jshint validthis:true */\n            this.when = sinon.stub();\n            this.otherwise = sinon.stub();\n\n            this.$get = function() {\n                return {\n                    // current: {},  // fake before each test as needed\n                    // routes:  {}  // fake before each test as needed\n                    // more? You'll know when it fails :-)\n                    _faked: 'this is the faked $route service'\n                };\n            };\n        });\n    }\n\n    function fakeStateProvider($provide) {\n        /**\n         * Stub out the $stateProvider so we avoid\n         * all routing calls, including the default state\n         * which runs on every test otherwise.\n         * Make sure this goes before the inject in the spec.\n         *\n         * Optionally set up the fake behavior in your tests by monkey patching\n         * the faked $state router. For example:\n         *\n         * beforeEach(function() {\n         *      // get fake $state router service\n         *      bard.inject(this, '$state');\n         *\n         *      // plug in fake $state router values for this set of tests\n         *      $state.current = { ... fake values here ... };\n         *      $state.state   = { ... fake values here ... };\n         *  })\n         */\n        $provide.provider('$state', function() {\n            /* jshint validthis:true */\n            this.state = sinon.stub();\n\n            this.$get = function() {\n                return {\n                    // current: {},  // fake before each test as needed\n                    // state:  {}  // fake before each test as needed\n                    // more? You'll know when it fails :-)\n                    _faked: 'this is the faked $state service'\n                };\n            };\n        });\n        $provide.provider('$urlRouter', function() {\n            /* jshint validthis:true */\n            this.otherwise = sinon.stub();\n\n            this.$get = function() {\n                return {\n                    // current: {},  // fake before each test as needed\n                    // states:  {}  // fake before each test as needed\n                    // more? You'll know when it fails :-)\n                    _faked: 'this is the faked $urlRouter service'\n                };\n            };\n        });\n    }\n\n    /**\n     * Get the spec context from parameters (if there)\n     * or from `this` (if it is the ctx as a result of `bind`)\n     */\n    function getCtxFromArgs(args) {\n        var ctx;\n        var first = args[0];\n        // heuristic to discover if the first arg is the mocha spec context (`this`)\n        if (first && first.test) {\n            // The first arg was the mocha spec context (`this`)\n            // Get it and strip it from args\n            ctx = args.shift();\n        } else if (this.test) {\n            // alternative: caller can bind bardInject to the spec context\n            ctx = this;\n        }\n        return ctx;\n    }\n\n    /**\n     * Inspired by Angular; that's how they get the parms for injection\n     * Todo: no longer used by `injector`. Remove?\n     */\n    function getFnParams(fn) {\n        var fnText;\n        var argDecl;\n\n        var FN_ARGS = /^function\\s*[^\\(]*\\(\\s*([^\\)]*)\\)/m;\n        var FN_ARG_SPLIT = /,/;\n        var FN_ARG = /^\\s*(_?)(\\S+?)\\1\\s*$/;\n        var STRIP_COMMENTS = /((\\/\\/.*$)|(\\/\\*[\\s\\S]*?\\*\\/))/mg;\n        var params = [];\n        if (fn.length) {\n            fnText = fn.toString().replace(STRIP_COMMENTS, '');\n            argDecl = fnText.match(FN_ARGS);\n            angular.forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {\n                arg.replace(FN_ARG, function(all, underscore, name) {\n                    params.push(name);\n                });\n            });\n        }\n        return params;\n    }\n\n    function isSpecRunning() { return !!currentSpec; }\n\n    /**\n     * Mocks out a service with sinon stubbed functions\n     * that return the values specified in the config\n     *\n     * If the config value is `undefined`,\n     * stub the service method with a dummy that doesn't return a value\n     *\n     * If the config value is a function, set service property with it\n     *\n     * If a service member is a property, not a function,\n     * set it with the config value\n\n     * If a service member name is not a key in config,\n     * follow the same logic as above to set its members\n     * using the config._default value (which is `undefined` if omitted)\n     *\n     * If there is a config entry that is NOT a member of the service\n     * add mocked function to the service using the config value\n     *\n     * Usage:\n     *   Given this DoWork service:\n     *      {\n     *          doWork1:  an async function,\n     *          doWork2:  a function,\n     *          doWork3:  an async function,\n     *          doWork4:  a function,\n     *          isActive: true\n     *      }\n     *\n     *   Given this config:\n     *      {\n     *          doWork1:  $q.when([{name: 'Bob'}, {name: 'Sally'}]),\n     *          doWork2:  undefined,\n     *          //doWork3: not in config therefore will get _default value\n     *          doWork4:  an alternate doWork4 function\n     *          doWork5:  $q.reject('bad boy!')\n     *          isActive: false,\n     *          _default: $q.when([])\n     *      }\n     *\n     *   Service becomes\n     *      {\n     *          doWork1:  a stub returning $q.when([{name: 'Bob'}, {name: 'Sally'}]),\n     *          doWork2:  do-nothing stub,\n     *          doWork3:  a stub returning $q.when([]),\n     *          doWork4:  an alternate doWork4 function,\n     *          doWork5:  a stub returning $q.reject('bad boy!'),\n     *          isActive: false,\n     *      }\n     */\n    function mockService(service, config) {\n\n        var serviceKeys = [];\n        for (var key in service) {\n            serviceKeys.push(key);\n        }\n\n        var configKeys = [];\n        for (var key in config) {\n            configKeys.push(key);\n        }\n\n        angular.forEach(serviceKeys, function(key) {\n            var value = configKeys.indexOf(key) > -1 ?\n                config[key] : config._default;\n\n            if (typeof service[key] === 'function') {\n                if (typeof value === 'function') {\n                    service[key] = value;\n                } else {\n                    sinon.stub(service, key, function() {\n                        return value;\n                    });\n                }\n            } else {\n                service[key] = value;\n            }\n        });\n\n        // for all unused config entries add a sinon stubbed\n        // async method that returns the config value\n        angular.forEach(configKeys, function(key) {\n            if (serviceKeys.indexOf(key) === -1) {\n                var value = config[key];\n                if (typeof value === 'function') {\n                    service[key] = value;\n                } else {\n                    service[key] = sinon.spy(function() {\n                        return value;\n                    });\n                }\n            }\n        });\n\n        return service;\n    }\n\n    /**\n     *  Listen to mocha test runner events\n     *  Usage in browser:\n     *     var runner = mocha.run();\n     *     bard.mochaRunnerListener(runner);\n     */\n    function mochaRunnerListener(runner) {\n        if (!global.mocha) { return; }\n        if (!runner.ignoreLeaks) {\n            runner.on('hook end', addOkGlobals);\n        };\n\n        // When checking global leaks with mocha.checkLeaks()\n        // make sure mocha is aware of bard's okGlobals\n        function addOkGlobals(hook) {\n            // HACK: only way I've found so far to ensure that bard added globals\n            // are always inspected. Using private mocha _allowedGlobals (shhhh!)\n            if (okGlobals.length && !hook._allowedGlobals) {\n                hook._allowedGlobals = okGlobals;\n            }\n        }\n    }\n\n    // Replaces the accented characters of many European languages w/ unaccented chars\n    // Use it in JavaScript string sorts where such characters may be encountered\n    // Matches the default string comparers of most databases.\n    // Ex: replaceAccentChars(a.Name) < replaceAccentChars(b.Name)\n    // instead of:            a.Name  <                    b.Name\n    function replaceAccentChars(s) {\n        var r = s.toLowerCase();\n        r = r.replace(new RegExp(/[àáâãäå]/g), 'a');\n        r = r.replace(new RegExp(/æ/g), 'ae');\n        r = r.replace(new RegExp(/ç/g), 'c');\n        r = r.replace(new RegExp(/[èéêë]/g), 'e');\n        r = r.replace(new RegExp(/[ìíîï]/g), 'i');\n        r = r.replace(new RegExp(/ñ/g), 'n');\n        r = r.replace(new RegExp(/[òóôõö]/g), 'o');\n        r = r.replace(new RegExp(/œ/g), 'oe');\n        r = r.replace(new RegExp(/[ùúûü]/g), 'u');\n        r = r.replace(new RegExp(/[ýÿ]/g), 'y');\n        return r;\n    }\n\n    /**\n     *  Assert that there are no outstanding HTTP requests after test is complete\n     *  For use with ngMocks; doesn't work for async server integration tests\n     */\n    function verifyNoOutstandingHttpRequests () {\n        afterEach(angular.mock.inject(function($httpBackend) {\n            $httpBackend.verifyNoOutstandingExpectation();\n            $httpBackend.verifyNoOutstandingRequest();\n        }));\n    }\n\n    /**\n     * Returns a function that execute a callback function\n     * (typically a fn making asserts) within a try/catch\n     * The try/catch then calls the ambient \"done\" function\n     * in the appropriate way for both success and failure\n     *\n     * Useage:\n     *    bard.inject('ngRouteTester', ...); // see bard-ngRouteTester.js\n     *    ...\n     *    // When the DOM is ready, assert got the dashboard view\n     *    ngRouteTester.until(elemIsReady, wrap(hasDashboardView, done));\n     */\n    function wrapWithDone(callback, done) {\n        return function() {\n            try {\n                callback();\n                done();\n            } catch (err) {\n                done(err);\n            }\n        };\n    }\n\n    /*\n     *  Phantom.js does not support Function.prototype.bind (at least not before v.2.0\n     *  That's just crazy. Everybody supports bind.\n     *  Read about it here: https://groups.google.com/forum/#!msg/phantomjs/r0hPOmnCUpc/uxusqsl2LNoJ\n     *  This polyfill is copied directly from MDN\n     *  https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Compatibility\n     */\n    function addBindPolyfill() {\n        if (Function.prototype.bind) { return; } // already defined\n\n        /*jshint freeze: false */\n        Function.prototype.bind = function (oThis) {\n            if (typeof this !== 'function') {\n                // closest thing possible to the ECMAScript 5\n                // internal IsCallable function\n                throw new TypeError(\n                    'Function.prototype.bind - what is trying to be bound is not callable');\n            }\n\n            var aArgs = Array.prototype.slice.call(arguments, 1),\n                fToBind = this,\n                FuncNoOp = function () {},\n                fBound = function () {\n                    return fToBind.apply(this instanceof FuncNoOp && oThis ? this : oThis,\n                        aArgs.concat(Array.prototype.slice.call(arguments)));\n                };\n\n            FuncNoOp.prototype = this.prototype;\n            fBound.prototype = new FuncNoOp();\n\n            return fBound;\n        };\n    }\n\n})();\n"
  },
  {
    "path": "gulp.config.js",
    "content": "module.exports = function() {\n    var root = './';\n    var service = {\n        getConfig: getConfig\n    };\n    return service;\n\n    function getConfig() {\n        var config = {\n            specs: ['./tests/**/*.spec.js'],\n            js: [\n                './bard.js',\n                './bard-ngRouteTester.js'\n            ],\n            packages: [\n                './package.json',\n                './bower.json'\n            ],\n            build: './dist/',\n            report: './report/',\n            root: root\n        };\n\n        return config;\n    }\n};\n"
  },
  {
    "path": "gulpfile.js",
    "content": "var gulp = require('gulp');\nvar args = require('yargs').argv;\nvar config = require('./gulp.config')().getConfig();\nvar del = require('del');\nvar glob = require('glob');\nvar _ = require('lodash');\nvar path = require('path');\nvar $ = require('gulp-load-plugins')({lazy: true});\n\nvar colors = $.util.colors;\nvar env = $.util.env;\n\n/**\n * List the available gulp tasks\n */\ngulp.task('help', $.taskListing);\ngulp.task('default', ['help']);\n\n/**\n * Lint the code, create coverage report, and a visualizer\n * @return {Stream}\n */\ngulp.task('vet', function() {\n    log('Analyzing source with JSHint and JSCS');\n\n    return gulp\n        .src(config.js)\n        .pipe($.if(env.verbose, $.print()))\n        .pipe($.jshint.reporter('jshint-stylish'))\n        .pipe($.jscs());\n});\n\n/**\n * Bump the version\n * --type=pre will bump the prerelease version *.*.*-x\n * --type=patch or no flag will bump the patch version *.*.x\n * --type=minor will bump the minor version *.x.*\n * --type=major will bump the major version x.*.*\n * --version=1.2.3 will bump to a specific version and ignore other flags\n */\ngulp.task('bump', function() {\n    var msg = 'Bumping versions';\n    var type = args.type;\n    var version = args.ver;\n    var options = {};\n    if (version) {\n        options.version = version;\n        msg += ' to ' + version;\n    } else {\n        options.type = type;\n        msg += ' for a ' + type;\n    }\n    log(msg);\n\n    return gulp\n        .src(config.packages)\n        .pipe($.print())\n        .pipe($.bump(options))\n        .pipe(gulp.dest(config.root));\n});\n\n/**\n * Build everything\n */\ngulp.task('build', ['clean'], function(done) {\n    log('Optimizing the js, css, and html');\n\n    var stream = gulp\n        .src(config.js)\n        .pipe(getHeader())\n        .pipe(gulp.dest(config.build))\n        .pipe($.uglify())\n        .pipe(getHeader())\n        .pipe($.rename('bard.min.js'))\n        .pipe(gulp.dest(config.build))\n        .on('end', success)\n        .on('error', error);\n\n    function error(err) {\n        log(err);\n        done(err);\n    }\n\n    function success() {\n        var msg = {\n            title: 'gulp build',\n            message: 'Deployed to the dist folder'\n        };\n        log(msg);\n        notify(msg);\n        done();\n    }\n});\n\n/**\n * Remove all files from the build, temp, and reports folders\n * @param  {Function} done - callback when complete\n */\ngulp.task('clean', function(done) {\n    var delconfig = [].concat(config.build, config.report);\n    log('Cleaning: ' + $.util.colors.blue(delconfig));\n    del(delconfig, done);\n});\n\n/**\n * Delete all files in a given path\n * @param  {Array}   path - array of paths to delete\n * @param  {Function} done - callback when complete\n */\nfunction clean(path, done) {\n    log('Cleaning: ' + $.util.colors.blue(path));\n    del(path, done);\n}\n\n/**\n * Formatter for bytediff to display the size changes after processing\n * @param  {Object} data - byte data\n * @return {String}      Difference in bytes, formatted\n */\nfunction bytediffFormatter(data) {\n    var difference = (data.savings > 0) ? ' smaller.' : ' larger.';\n    return data.fileName + ' went from ' +\n        (data.startSize / 1000).toFixed(2) + ' kB to ' +\n        (data.endSize / 1000).toFixed(2) + ' kB and is ' +\n        formatPercent(1 - data.percent, 2) + '%' + difference;\n}\n\n/**\n * Format a number as a percentage\n * @param  {Number} num       Number to format as a percent\n * @param  {Number} precision Precision of the decimal\n * @return {String}           Formatted perentage\n */\nfunction formatPercent(num, precision) {\n    return (num * 100).toFixed(precision);\n}\n\n/**\n * Format and return the header for files\n * @return {String}           Formatted file header\n */\nfunction getHeader() {\n    var pkg = require('./package.json');\n    var template = ['/**',\n        ' * <%= pkg.name %> - <%= pkg.description %>',\n        ' * @authors <%= pkg.authors %>',\n        ' * @version v<%= pkg.version %>',\n        ' * @link <%= pkg.homepage %>',\n        ' * @license <%= pkg.license %>',\n        ' */',\n        ''\n    ].join('\\n');\n    return $.header(template, {\n        pkg: pkg\n    });\n}\n\n/**\n * Log a message or series of messages using chalk's blue color.\n * Can pass in a string, object or array.\n */\nfunction log(msg) {\n    if (typeof(msg) === 'object') {\n        for (var item in msg) {\n            if (msg.hasOwnProperty(item)) {\n                $.util.log($.util.colors.blue(msg[item]));\n            }\n        }\n    } else {\n        $.util.log($.util.colors.blue(msg));\n    }\n}\n\n/**\n * Show OS level notification using node-notifier\n */\nfunction notify(options) {\n    var notifier = require('node-notifier');\n    var notifyOptions = {\n        sound: 'Bottle',\n        contentImage: path.join(__dirname, 'gulp.png'),\n        icon: path.join(__dirname, 'gulp.png')\n    };\n    _.assign(notifyOptions, options);\n    notifier.notify(notifyOptions);\n}\n"
  },
  {
    "path": "index.html",
    "content": "<!DOCTYPE html>\n<html>\n<head lang=\"en\">\n    <meta charset=\"UTF-8\">\n    <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge, chrome=1\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no\" />\n    <title>bardjs tests</title>\n\n    <style>\n        body {\n            font: 20px/1.5 \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n            padding-left: 20px;\n        }\n    </style>\n\n    <!--BEWARE of using any app styles as @media can screw up tests -->\n\n    <!-- inject-testvendorcss:css -->\n    <link rel=\"stylesheet\" href=\"node_modules/mocha/mocha.css\">\n    <!-- endinject -->\n\n</head>\n<body>\n\n<h1><a href=\"specs.html\">bardjs tests</a></h1>\n\n\n<div id=\"mocha\"></div>\n\n\n    <!-- inject-testharness:js -->\n    <script src=\"node_modules/mocha/mocha.js\"></script>\n    <script src=\"node_modules/chai/chai.js\"></script>\n    <script src=\"node_modules/mocha-clean/index.js\"></script>\n    <script src=\"bower_components/sinon/index.js\"></script>\n    <script src=\"node_modules/sinon-chai/lib/sinon-chai.js\"></script>\n    <!-- endinject -->\n\n    <script>\n        expect = chai.expect;\n        AssertionError = chai.AssertionError;\n        mocha.setup('bdd');\n        mocha.traceIgnores = ['mocha.js', 'chai.js', 'angular.js'];\n    </script>\n\n    <!-- inject-testvendor:js -->\n    <script src=\"bower_components/angular/angular.js\"></script>\n    <script src=\"bower_components/angular-mocks/angular-mocks.js\"></script>\n    <!-- endinject -->\n\n    <!-- inject:js -->\n    <script src=\"bard.js\"></script>\n    <!-- endinject -->\n\n    <!-- inject-helpers:js -->\n    <!-- endinject -->\n\n    <!-- inject-specs:js -->\n    <script src=\"tests/bard.inject.spec.js\"></script>\n    <script src=\"tests/bard.mockService.spec.js\"></script>\n    <!-- endinject -->\n\n    <script>\n        mocha.run();\n    </script>\n\n</body>\n</html>"
  },
  {
    "path": "package.js",
    "content": "Package.describe({\n  name: 'firebait:bardjs',\n  version: '0.0.4',\n  // Brief, one-line summary of the package.\n  summary: 'bardjs is a small library of functions to help you write Angular v.1.x application tests.',\n  // URL to the Git repository containing the source code for this package.\n  git: 'https://github.com/firebait/bardjs.git',\n  // By default, Meteor will default to using README.md for documentation.\n  // To avoid submitting documentation, set this field to null.\n  documentation: 'README.md',\n  debugOnly: true\n});\n\nPackage.onUse(function(api) {\n  api.versionsFrom('1.2.0.2');\n  api.use([\n    'angular:angular@1.4.4',\n    'angular:angular-mocks@1.4.7',\n    'practicalmeteor:sinon@1.14.1_2'\n  ], 'client');\n  api.addFiles([\n    './dist/bard.js',\n    './dist/bard-ngRouteTester.js'], 'client');\n});\n\nPackage.onTest(function(api) {\n});\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"bardjs\",\n  \"version\": \"0.1.10\",\n  \"description\": \"Spec helpers for testing angular v.1.x apps with Mocha, Jasmine or QUnit\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/wardbell/bardjs.git\"\n  },\n  \"keywords\": [\n    \"angular\",\n    \"mocha\",\n    \"chai\",\n    \"mocks\",\n    \"testing\",\n    \"client-side\"\n  ],\n  \"authors\": [\n    \"John Papa\",\n    \"Ward Bell\"\n  ],\n  \"license\": \"MIT\",\n  \"homepage\": \"https://github.com/wardbell/bardjs\",\n  \"bugs\": {\n    \"url\": \"https://github.com/wardbell/bardjs/issues\"\n  },\n  \"scripts\": {\n    \"init\": \"npm install\"\n  },\n  \"dependencies\": {\n    \"sinon\": \"~1.15.0\"\n  },\n  \"devDependencies\": {\n    \"chai\": \"^1.9.1\",\n    \"del\": \"^1.1.0\",\n    \"glob\": \"^4.3.2\",\n    \"gulp\": \"^3.8.10\",\n    \"gulp-bump\": \"^0.2.2\",\n    \"gulp-bytediff\": \"^0.2.0\",\n    \"gulp-header\": \"^1.2.2\",\n    \"gulp-if\": \"^1.2.5\",\n    \"gulp-jscs\": \"^1.3.1\",\n    \"gulp-jshint\": \"^1.9.0\",\n    \"gulp-load-plugins\": \"^0.8.0\",\n    \"gulp-minify-html\": \"^0.1.7\",\n    \"gulp-print\": \"^1.1.0\",\n    \"gulp-rename\": \"^1.2.0\",\n    \"gulp-task-listing\": \"^1.0.0\",\n    \"gulp-uglify\": \"^1.0.2\",\n    \"gulp-util\": \"^3.0.1\",\n    \"jshint-stylish\": \"^1.0.0\",\n    \"karma\": \"^0.12.24\",\n    \"karma-chai\": \"^0.1.0\",\n    \"karma-chai-sinon\": \"^0.1.3\",\n    \"karma-chrome-launcher\": \"^0.1.4\",\n    \"karma-coverage\": \"^0.2.4\",\n    \"karma-firefox-launcher\": \"^0.1.3\",\n    \"karma-growl-reporter\": \"^0.1.1\",\n    \"karma-mocha\": \"^0.1.4\",\n    \"karma-phantomjs-launcher\": \"^0.1.4\",\n    \"karma-safari-launcher\": \"^0.1.1\",\n    \"karma-sinon\": \"^1.0.3\",\n    \"lodash\": \"^2.4.1\",\n    \"mocha-clean\": \"^0.4.0\",\n    \"node-notifier\": \"^4.0.3\",\n    \"phantomjs\": \"1.9.9\",\n    \"sinon-chai\": \"^2.6.0\",\n    \"yargs\": \"^3.5.4\"\n  }\n}\n"
  },
  {
    "path": "snippets/brackets-testing-snippets.yaml",
    "content": "# mocha/jasmine snippets\n\n- trigger: bdescribe\n  description: \"mocha/jasmine describe\"\n  scope: javascript\n  text: |\n        describe('${1:description}', function () {\n            ${2:}\n        });\n\n- trigger: bit\n  description: \"mocha/jasmine test (synchronous)\"\n  scope: javascript\n  text: |\n        it('${1:should}', function () {\n            ${2:}\n        });\n         \n- trigger: bait\n  description: \"asynchornous mocha/jasmine test\"\n  scope: javascript\n  text: |\n        it('${1:should}', function (done) {\n            ${2:}\n        });\n            \n- trigger: bbeforeEach\n  description: \"mocha/jasmine before-each-test\"\n  scope: javascript\n  text: |\n        beforeEach(function () {\n            ${1:}\n        });\n        \n- trigger: bafterEach\n  description: \"mocha/jasmine after-each-test\"\n  scope: javascript\n  text: |\n        afterEach(function () {\n            ${1:}\n        });\n        \n- trigger: bdone\n  description: \".then(done, done) - tail of async promise chain\"\n  scope: javascript\n  text: |\n        .then(done, done);\n        ${1:}\n        \n# chai expectation snippets\n# see http://chaijs.com/api/bdd/\n\n- trigger: bexpect\n  description: \"chai expect\"\n  scope: javascript\n  text: |\n        expect(${1:expected}).to.${2:};\n\n- trigger: bequal\n  description: \"chai expect to equal\"\n  scope: javascript\n  text: |\n        expect(${1:expected}).to.equal(${2:value});\n        \n- trigger: blen\n  description: \"chai expect to have length\"\n  scope: javascript\n  text: |\n        expect(${1:expected}).to.have.length(${2:length});\n        \n- trigger: bmatch\n  description: \"chai expect to match\"\n  scope: javascript\n  text: |\n        expect(${1:expected}).to.match(/${2:match}/i);\n        \n        \n- trigger: bprop\n  description: \"chai expect to have property\"\n  scope: javascript\n  text: |\n        expect(${1:expected}).to.have.property('${2:property}', ${3:value});\n        \n- trigger: bcalled\n  description: \"chai expect to have been called\"\n  scope: javascript\n  text: |\n        expect(${1:expected}).to.have.been.called${2:}; \n\n- trigger: bthrow\n  description: \"chai expect to throw\"\n  scope: javascript\n  text: |\n        expect(function () {\n            ${1:fn-that-throws};\n        }).to.throw(${2:Error}); \n  \n# bard.js snippets\n\n- trigger: binject\n  description: \"bard inject\"\n  scope: javascript\n  text: |\n        bard.inject(this, ${1:quoted-dependencies});\n        \n- trigger: bcinject\n  description: \"bard inject controller\"\n  scope: javascript\n  text: |\n        bard.inject(this, '$controller', '$q', '$rootScope', ${1:});\n        \n- trigger: bmodule\n  description: \"bard app module\"\n  scope: javascript\n  text: |\n        bard.appModule('${1:app}'${2:});\n      \n- trigger: basyncmodule\n  description: \"bard async module\"\n  scope: javascript\n  text: |\n        bard.asyncModule('${1:app}'${2:});\n        \n- trigger: bverify\n  description: \"bard.verifyNoOutstandingHttpRequests();\"\n  scope: javascript\n  text: |\n        bard.verifyNoOutstandingHttpRequests();\n        ${1:}\n  \n# angular test snippets\n\n- trigger: bapply\n  description: \"$rootScope.$apply();\"\n  scope: javascript\n  text: |\n        $rootScope.$apply();\n        ${1:}  \n\n- trigger: bwhen\n  description: \"$httpBackend.when(...).respond(...);\"\n  scope: javascript\n  text: |\n        $httpBackend.when('get', '${1:url}')\n                    .respond(${2:status}, {${3:data}});\n\n- trigger: bflush\n  description: \"$httpBackend.flush();\"\n  scope: javascript\n  text: |\n        $httpBackend.flush();\n        ${1:} \n  \n# miscellaneous snippets\n- trigger: bfn\n  description: \"function template\"\n  scope: javascript\n  text: |\n        function ${1:}() {\n            ${2:}\n        }\n"
  },
  {
    "path": "tests/bard.injector.spec.js",
    "content": "/* jshint -W117, -W030 */\ndescribe('bard.inject', function() {\n    'use strict';\n\n    var origDebugging;\n\n    before(function() {\n        origDebugging = bard.debugging();\n        // uncomment to turn bard debug logging on for this spec file\n        // bard.debugging(true);\n    });\n\n    after(function() {\n        bard.debugging(origDebugging); // restore bard debug logging\n    });\n\n    beforeEach(module(function($provide) {\n        // define a 'nutz' service for testing injector\n        $provide.service('nutz', function() {});\n    }));\n\n    beforeEach('bard.inject.spec top beforeEach', function() {\n        // Confirm no window pollution from a prior bard.inject() call\n        bard.log('bard.inject.spec top beforeEach');\n        expect(window.$log).to.not.exist;\n        expect(window.nutz).to.not.exist;\n        expect(window.baz).to.not.exist;\n        expect(window.foo).to.not.exist;\n    });\n\n    describe('(describe #1):', function() {\n        it('window.$log and window.nutz should not exist', function() {\n            expect(window.$log).to.not.exist;\n            expect(window.nutz).to.not.exist;\n        });\n    });\n\n    describe('(describe #2):', function() {\n\n        beforeEach('bard.inject.spec describe #2 beforeEach', function() {\n            bard.log('bard.inject.spec (describe #2) beforeEach');\n            bard.inject(this, ['$log', 'nutz']);\n        });\n\n        it('true is true', function() {\n            expect(true).to.be.true;\n        });\n\n        it('$log exists', function() {\n            expect($log).to.exist;\n        });\n\n        it('nutz exists', function() {\n            expect(nutz).to.exist;\n        });\n    });\n\n    describe('(describe #3):', function() {\n\n        beforeEach('bard.inject.spec describe #3 beforeEach', function() {\n            bard.log('bard.inject.spec (describe #3) beforeEach');\n            // window.$log and window.nutz should not exist before any test\n            expect(window.$log).to.not.exist;\n            expect(window.nutz).to.not.exist;\n        });\n\n        // Although inject() puts injectables in the window,\n        // it also removes them after each test\n        // Notice ... no private vars for $log or nutz!\n        // ... no injecting of them either.\n\n        it('should set window.$log and window.nutz when call inject w/ string params', function() {\n\n            bard.inject(this, '$log', 'nutz');\n\n            expect($log).to.exist;\n            expect(nutz).to.exist;\n\n            // They are actually in the window\n            expect(window.$log).to.exist;\n            expect(window.nutz).to.exist;\n\n        });\n\n        it('should set window.$log and window.nutz when call inject with string array', function() {\n\n            bard.inject(this, ['$log', 'nutz']);\n\n            expect($log).to.exist;\n            expect(nutz).to.exist;\n        });\n\n        it('should set window.$log and window.nutz when call inject with a function', function() {\n\n            bard.inject(this, function($log, nutz) {\n                // do stuff just as if we called ngMocks.inject\n                $log.info('use the injected $log');\n            });\n\n            expect($log).to.exist;\n            expect(nutz).to.exist;\n\n            expect($log.info.logs[0][0])\n                .to.equal('use the injected $log',\n                '$log.info should have been called: ');\n        });\n\n        // reinforcing the point that inject adds to globals, not local fn scope\n        it('locally defined $log hides the $log injected by inject', function() {\n            var $log; // declaration hides the one in window.$log created by inject\n\n            bard.inject.bind(this)('$q', '$log');\n\n            expect($log).to.not.exist;\n            expect(window.$log).to.exist;\n        });\n\n        it('should set window.$log & window.foo when call inject(\"$log\",\"block.foo\")', function() {\n            // register this ridiculous value for just this test\n            module(function($provide) {\n                $provide.value('block.foo', 'foo');\n            });\n\n            // Can inject a service with a dotted name!\n            bard.inject(this, '$log', 'block.foo');\n\n            expect($log).to.exist;\n            expect(foo).to.exist;\n            expect(window.foo).to.exist;\n        });\n\n         // This afterEach would fail because it is called BEFORE\n         // the outer one created by bard to handle window cleaning\n         // -----------------------------------------------------\n         // afterEach('Describe #2 afterEach', function() {\n         //     console.log('---Describe #2 afterEach');\n         //     // Should have cleaned up after itself\n         //     expect(window.$log).to.not.exist;\n         //     expect(window.nutz).to.not.exist;\n         // });\n    });\n\n    describe('(describe #4):', function() {\n        it('window.$log and window.nutz should not exist', function() {\n            expect(window.$log).to.not.exist;\n            expect(window.nutz).to.not.exist;\n        });\n    });\n\n    describe('(describe #5):', function() {\n        beforeEach(function() {\n            bard.log('bard.inject.spec (describe #5) beforeEach');\n            // register this ridiculous value for just this describe\n            module(function($provide) {\n                $provide.value('baz', 'baz');\n            });\n\n            bard.inject(this, 'baz'); // get baz in outer describe\n        });\n\n        describe('in nested describe', function() {\n            it('baz is available from parent describe', function() {\n                expect(baz).to.exist;\n            });\n\n            it('baz from inject() is same object as baz from direct injection', function() {\n\n                inject(function(_baz_) {\n                    expect(baz).to.equal(_baz_);\n                });\n            });\n        });\n    });\n});\n"
  },
  {
    "path": "tests/bard.mockService.spec.js",
    "content": "/* jshint -W117, -W030 */\ndescribe('bard.mockService', function() {\n    'use strict';\n\n    var mockService = bard.mockService;\n    var flush;\n    var sandbox;\n\n    beforeEach(function() {\n        module();\n        bard.inject(this, '$q', '$rootScope', '$window');\n        sandbox = sinon.sandbox.create();\n        flush = function() { $rootScope.$apply(); };\n    });\n\n    afterEach(function() {\n        sandbox.restore();\n    });\n\n    describe('when execute the \"real\" DoWork service described in the usage example', function() {\n        var service;\n\n        beforeEach(function() {\n            service = getDoWorkService();\n        });\n\n        it('`doWork1` returns a resolved promise with the \"real\" results', function() {\n            service.doWork1(1, 2)\n                .then(function(results) {\n                    expect(results).to.deep.equal([1, 2]);\n                });\n            flush();\n        });\n\n        it('`doWork2` calls alert and returns the \"real\" results', function() {\n            var alert = sandbox.stub($window, 'alert');\n            bard.addGlobals(this, 'alert'); // because sinon adds it!\n            var results = service.doWork2();\n            expect(results).to.equal('pointless');\n            expect(alert).to.have.been.calledWith('Hi there');\n        });\n\n        it('`doWork3` returns a resolved promise with the \"real\" results', function() {\n            service.doWork3(1, 2)\n                .then(function(results) {\n                    expect(results).to.deep.equal(['a1', 'a2']);\n                });\n            flush();\n        });\n\n        it('`doWork4` returns the \"real\" results', function() {\n            var results = service.doWork4(1, 2);\n            expect(results).to.equal('Hi from doWork4');\n        });\n\n        it('does not have a `doWork5`', function() {\n            expect(service).to.not.have.property('doWork5');\n        });\n        \n        it('`doWorkProto` return the \"real\" results', function() {\n            var results = service.doWorkProto();\n            expect(results).to.be.true;\n        });\n\n        it('`isActive` should be true', function() {\n            expect(service.isActive).to.be.true;\n        });\n    });\n\n    describe('when mock the DoWork service as described in the usage example', function() {\n        var service;\n\n        beforeEach(function() {\n            service = mockService(getDoWorkService(),\n            {   // config in the usage example\n                doWork1:  $q.when([{name: 'Bob'}, {name: 'Sally'}]),\n                doWork2:  undefined,\n                doWork4:  function() { return 'Now for a different kind of work';},\n                doWork5:  $q.reject('bad boy!'),\n                isActive: false,\n                _default: $q.when([])\n            });\n        });\n\n        it('`doWork1` returns a resolved promise with the fake results', function() {\n            service.doWork1(1, 2)\n                .then(function(results) {\n                    expect(results).to.deep.equal([{name: 'Bob'}, {name: 'Sally'}]);\n                });\n            // verify `doWork1` is a spy\n            expect(service.doWork1).to.have.been.calledWith(1, 2);\n            flush();\n        });\n\n        it('`doWork2` returns nothing', function() {\n            var results = service.doWork2(1, 2);\n            expect(results).to.not.be.defined;\n            // verify `doWork2` is a spy\n            expect(service.doWork2).to.have.been.calledWith(1, 2);\n        });\n\n        it('`doWork3` returns a resolved promise with config._default (empty array)', function() {\n            service.doWork3(1, 2).then(expectEmptyArray);\n            // verify `doWork3` is a spy\n            expect(service.doWork3).to.have.been.calledWith(1, 2);\n            flush();\n        });\n\n        it('`doWork4` returns the fake results', function() {\n            var results = service.doWork4(1, 2);\n            expect(results).to.match(/different/);\n            // verify `doWork4` is NOT a spy\n            expect(service.doWork4).to.not.have.property('restore');\n        });\n\n        it('`doWork5` returns a rejected promise with the faked error', function() {\n            service.doWork5()\n                .then(function() {\n                    // Should not come here!\n                    expect('should have failed').to.be.true;\n                })\n                .catch(function(err) {\n                    expect(err).to.match(/bad/);\n                });\n            // verify `doWork5` is a spy\n            expect(service.doWork5).to.have.been.called;\n            flush();\n        });\n        \n        it('`doWorkProto` returns `_default` value', function() {\n            service.doWorkProto(1, 2).then(expectEmptyArray);\n            // verify `doWork3` is a spy\n            expect(service.doWorkProto).to.have.been.calledWith(1, 2);\n            flush();\n        });\n\n        it('`isActive` should have changed to false', function() {\n            expect(service.isActive).to.be.false;\n        });\n    });\n\n    describe('when mock one async method of the DoWork service and default the rest', function() {\n        // typical usage when mocking dataservice for a controller\n        // mock the method(s) of interest; let the others do the minimum necessary\n        var service;\n\n        beforeEach(function() {\n            service = mockService(getDoWorkService(),\n            {   // config in the usage example\n                doWork1:  $q.when([1, 2, 3]),\n                _default: $q.when([])\n            });\n        });\n\n        it('`doWork1` returns a resolved promise with the fake results', function() {\n            service.doWork1('foo').then(function(results) {\n                expect(results).to.deep.equal([1, 2, 3]);\n            });\n            flush();\n        });\n\n        it('`doWork2`-`doWork4` each return resolved promise with empty array', function() {\n            service.doWork2('could').then(expectEmptyArray);\n            service.doWork3('be').then(expectEmptyArray);\n            service.doWork4('anything').then(expectEmptyArray);\n            flush();\n        });\n    });\n\n    describe('when mock one async method of the DoWork service and omit _default', function() {\n        var service;\n\n        beforeEach(function() {\n            service = mockService(getDoWorkService(),\n            {   // config in the usage example\n                doWork1:  $q.when([1, 2, 3])\n            });\n        });\n\n        it('`doWork1` returns a resolved promise with the fake results', function() {\n            service.doWork1('foo').then(function(results) {\n                expect(results).to.deep.equal([1, 2, 3]);\n            });\n            flush();\n        });\n\n        it('`doWork2`-`doWork4` are stubbed to return nothing', function() {\n            expect(service.doWork2('could')).to.not.be.defined;\n            expect(service.doWork3('be')).to.not.be.defined;\n            expect(service.doWork4('anything')).to.not.be.defined;\n            // but they are stubbed\n            expect(service.doWork2).to.have.been.calledWith('could');\n            expect(service.doWork3).to.have.been.calledWith('be');\n            expect(service.doWork4).to.have.been.calledWith('anything');\n\n            flush();\n        });\n    });\n\n    ///// helpers /////\n\n    // create the example DoWork service from bard.mockService usage doc\n    function getDoWorkService() {\n        var doWorkParent = {\n            doWorkProto: function() {\n                return true;\n            }\n        }\n        \n        var doWorkService = Object.create(doWorkParent)\n        \n        angular.extend(doWorkService, {\n            doWork1:  function doWork1(a, b) {\n                    return $q.when([].slice.apply(arguments));\n                },\n            doWork2:  function doWork2() {\n                    $window.alert('Hi there'); // something we do NOT want to do in a test\n                    return 'pointless';\n                },\n            doWork3:  function doWork3() {\n                    var args = [].slice.apply(arguments);\n                    // (1, 2) -> [a1, a2]\n                    var results = args.map(function(a) { return 'a' + a;});\n                    return $q.when(results);\n                },\n            doWork4:  function() {\n                return 'Hi from doWork4';\n            },\n            isActive: true\n        });\n        \n        return doWorkService;\n    }\n\n    function expectEmptyArray(results) {\n        expect(results).to.deep.equal([]);\n    }\n});\n"
  }
]