Repository: wardbell/bardjs
Branch: master
Commit: fff64e2bcf1b
Files: 20
Total size: 120.1 KB
Directory structure:
gitextract_mypoqgw8/
├── .editorconfig
├── .gitignore
├── .jscsrc
├── .jshintrc
├── CHANGELOG.md
├── LICENSE
├── README.md
├── bard-ngRouteTester.js
├── bard.js
├── bower.json
├── dist/
│ ├── bard-ngRouteTester.js
│ └── bard.js
├── gulp.config.js
├── gulpfile.js
├── index.html
├── package.js
├── package.json
├── snippets/
│ └── brackets-testing-snippets.yaml
└── tests/
├── bard.injector.spec.js
└── bard.mockService.spec.js
================================================
FILE CONTENTS
================================================
================================================
FILE: .editorconfig
================================================
# top-most EditorConfig file
root = true
# Unix-style newlines with a newline ending every file
[*]
indent_style = space
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
================================================
FILE: .gitignore
================================================
# Ignore Visual Studio Project #
###################
*.user
*.gpState
*.suo
bin
obj
/packages
# Ignore Node & Bower
###################
node_modules
/src/client/build
/src/build
bower_components
/report
**/test/coverage
# mongo db
###################
#Don't commit Mongo Database files
*.lock
*.0
*.1
*.ns
journal
# Ignore Web Storm #
.idea
# Compiled source #
###################
*.com
*.class
*.dll
*.exe
*.o
*.so
# Packages #
############
# it's better to unpack these files and commit the raw source
# git has its own built in compression methods
*.7z
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.xap
*.zip
# Logs and databases #
######################
*.log
*.sql
*.sqlite
# *.sdf
*.mdf
*.ldf
# OS generated files #
######################
.DS_Store*
ehthumbs.db
Icon?
Thumbs.db
packages
~$*.pp*
# Plato generated files #
######################
/report
# Meteor #
#####################
.versions
================================================
FILE: .jscsrc
================================================
{
"excludeFiles": ["node_modules/**", "bower_components/**"],
"requireCurlyBraces": [
"if",
"else",
"for",
"while",
"do",
"try",
"catch"
],
"requireOperatorBeforeLineBreak": true,
"requireCamelCaseOrUpperCaseIdentifiers": true,
"maximumLineLength": {
"value": 100,
"allowComments": true,
"allowRegex": true
},
"validateIndentation": 4,
"validateQuoteMarks": "'",
"disallowMultipleLineStrings": true,
"disallowMixedSpacesAndTabs": true,
"disallowTrailingWhitespace": true,
"disallowSpaceAfterPrefixUnaryOperators": true,
"disallowMultipleVarDecl": null,
"requireSpaceAfterKeywords": [
"if",
"else",
"for",
"while",
"do",
"switch",
"return",
"try",
"catch"
],
"requireSpaceBeforeBinaryOperators": [
"=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=",
"&=", "|=", "^=", "+=",
"+", "-", "*", "/", "%", "<<", ">>", ">>>", "&",
"|", "^", "&&", "||", "===", "==", ">=",
"<=", "<", ">", "!=", "!=="
],
"requireSpaceAfterBinaryOperators": true,
"requireSpacesInConditionalExpression": true,
"requireSpaceBeforeBlockStatements": true,
"requireLineFeedAtFileEnd": true,
"disallowSpacesInsideObjectBrackets": "all",
"disallowSpacesInsideArrayBrackets": "all",
"disallowSpacesInsideParentheses": true,
"validateJSDoc": {
"checkParamNames": true,
"requireParamTypes": true
},
"disallowMultipleLineBreaks": true,
"disallowCommaBeforeLineBreak": null,
"disallowDanglingUnderscores": null,
"disallowEmptyBlocks": null,
"disallowMultipleLineStrings": null,
"disallowTrailingComma": null,
"requireCommaBeforeLineBreak": null,
"requireDotNotation": null,
"requireMultipleVarDecl": null,
"requireParenthesesAroundIIFE": true
}
================================================
FILE: .jshintrc
================================================
{
"bitwise": true,
"camelcase": true,
"curly": true,
"eqeqeq": true,
"es3": false,
"forin": true,
"freeze": true,
"immed": true,
"indent": 4,
"latedef": "nofunc",
"newcap": true,
"noarg": true,
"noempty": true,
"nonbsp": true,
"nonew": true,
"plusplus": false,
"quotmark": "single",
"undef": true,
"unused": false,
"strict": false,
"maxparams": 10,
"maxdepth": 5,
"maxstatements": 40,
"maxcomplexity": 8,
"maxlen": 120,
"asi": false,
"boss": false,
"debug": false,
"eqnull": true,
"esnext": false,
"evil": false,
"expr": false,
"funcscope": false,
"globalstrict": false,
"iterator": false,
"lastsemic": false,
"laxbreak": false,
"laxcomma": false,
"loopfunc": true,
"maxerr": false,
"moz": false,
"multistr": false,
"notypeof": false,
"proto": false,
"scripturl": false,
"shadow": false,
"sub": true,
"supernew": false,
"validthis": false,
"noyield": false,
"browser": true,
"node": true,
"globals": {
"angular": false
}
}
================================================
FILE: CHANGELOG.md
================================================
bardjs Change Log
===================
### 0.1.10
- no functional changes.
- sinon moved its release file so we are now using bower to get sinon directly. which is better, anyway
### 0.1.8
- no functional changes.
- 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.
### 0.1.7
- no functional changes.
- 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
own node_modules folder.
### 0.1.6
- no functional changes
- updated package.json and bower.json descriptions to make clear that bardjs works w/ Jasmine and QUnit too
- removed package.json install script that invoked bower ... which might not be installed by those who load bard with npm
### 0.1.5
- no functional changes
- added explanatory comments to $state and $route router fakes
### 0.1.4
- updated dependency versioning
### 0.1.3
- documentation about dependence on sinon
- more robust handling of `this` when not using mocha; see [issue #5](https://github.com/wardbell/bardjs/issues/5).
### 0.1.2
- handle services that have prototype methods/attributes; see
[pr #4](https://github.com/wardbell/bardjs/pull/4).
### 0.1.1
- incorporate `Function.bind` polyfill (for testing in phantom.js)
### 0.1.0
- added brackets code snippets (draft)
### 0.0.9
- 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.
### 0.0.8
- bard.inject should work for QUnit too (removed mocha/jasmine limitation).
- Need QUnit tests.### 0.0.6
- heavily revamped bard.inject. added diagnostic bard.debug
### 0.0.7
- bard.inject no longer uses evil Function; added addGlobals, mochaRunnerListener
### Coming Soon
================================================
FILE: LICENSE
================================================
The MIT License (MIT)
Copyright (c) 2014, 2015 Ward Bell
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
# bardjs Test Helpers
[](https://www.npmjs.com/package/bardjs)
**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").
What kind of help? Help with **routine tasks** that would otherwise clutter your tests and obscure their intent.
The 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.
The [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.
# Installation
Most folks bardjs install it with [bower](http://bower.io/search/?q=bardjs "bard on bower") or [npm](https://www.npmjs.com/package/bardjs):
`bower install bardjs`
`npm install bardjs`
You can also clone [bardjs from github](https://github.com/wardbell/bardjs "bard on github") and extract *bard.js*itself.
>bard depends on [sinon.js](http://sinonjs.org/) so make sure you have that library available; bower and npm bring that down for you.
Almost all of bard is in the *bard.js* file within the *dist* folder.
If you're running tests in a browser, add the appropriate script tag *below* the script for your test framework library:
You'll need to add *sinon.js* as well
## karma considerations
If 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.
Be sure to include *sinon* among the karma frameworks as in this example extract:
frameworks: ['mocha', 'chai', 'sinon', 'chai-sinon'],
In 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").
# bard methods
After loading `bard.js`, you'll find the global variable `bard` at your finger tips as you write your tests.
The bard methods are listed right at the top of the *bard.js* file.
We won't describe every method here. Each method is prefaced in the code with it own documentation in comments describing both purpose and usage.
But we will call out the methods that have proven most notable and useful:
* [appModule](#appModule) - identify the application module to test and also disable certain routine services.
* [asyncModule](#asyncModule) - enable async integration testing by restoring `$http` and `$q` while identifying the application module to test.
* [inject](#inject) - inject angular and application components and store them by name on the global `window` object.
* [fake services](#fakeServices) - register disabled services that you can spy on.
* [log](#log) - writes messages to `console` when bard debugging is turned on.
* [mockService](#mockService) - create a mock for any service with spies and return values for every service member.
## appModule
**Identify the application module to test and also disable certain routine services.**
You 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").
We found that we routinely disable certain services at the same time.
For 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.
We 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.
The bard `appModule` method is a quick way to both identify the module to test and disable the *toastr* and routing services. This one line ...
`beforeEach(bard.appModule('myModule'));`
does the work of these seven ...
beforeEach(angular.mock.module(
'myModule',
bard.fakeToastr,
bard.fakeRouteHelperProvider,
bard.fakeRouteProvider,
bard.fakeStateProvider)
);
>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.
Like 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:
`beforeEach(bard.appModule('myModule', someDecorator, someMock));`
### don't use *appModule* when testing routes
You 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.
Instead, simply fall back to `angular.mock.module`, adding specific fakes as desired:
`beforeEach(module('myModule', bard.fakeToastr));`
## asyncModule
**Enable async integration testing by restoring `$httpBackend` and `$q` while identifying the application module to test.**
The [`angular.mock.module` function](https://docs.angularjs.org/api/ngMock/function/angular.mock.module "mock module") replaces `$httpBackend` and `$q` with mocked versions.
The 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.
These 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.
For 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?
You'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.
The 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:
`beforeEach(bard.asyncModule('app'));`
This is the equivalent of ...
beforeEach(module('app', bard.$httpBackendReal, bard.$qReal, bard.fakeToastr));
>The bard library's `$httpBackendReal` and `$qReal` restore the original angular `$httpBackend` and `$q` implementations; they may be invoked independently.
>
>We're also faking *toastr* for the same reason we faked it in [`appModule`](#appModule).
Now you write asynchronous tests that look a lot like production code. Here's a mocha example:
it('should get at least 6 Avengers', function (done) {
dataservice
.getAvengers()
.then(function(data) {
expect(data).to.have.length.above(6);
})
.then(done, done);
});
You 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.
Like 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:
`beforeEach(bard.asyncModule('app', someDecorator, someMock));`
## inject
**Inject angular and application components and store them by name on the global `window` object.**
The `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.
Here's how you might use `inject` within a `beforeEach` to get five dependent services while testing an Angular controller:
bard.inject(this, '$controller', '$log', '$q', '$rootScope', 'dataservice');
Now you can refer to these services by name in subsequent test functions as in these examples:
var controller = $controller('Avengers');
sinon.stub(dataservice, 'getAvengers').returns($q.when(avengers));
$rootScope.$apply();
expect(dataservice.getAvengers).to.have.been.calledOnce;
expect($log.error.logs[0]).to.match(/doomed/);
Compare the simplicity of
bard.inject(this, '$controller', '$log', '$q', '$rootScope', 'dataservice');
to the typical approach without bard:
// declare local variables for use within subsequent test functions
var $controller, $log, $q, $rootScope, dataservice;
// inject the services using Angular "underscore wrapping"
beforeEach(inject(function(_$controller_, _$log_, _$q_, _$rootScope_, _dataservice_) {
// wire local vars to the injected services
$controller = _$controller_;
$log = _$log_;
$q = _$q_;
$rootScope = _$rootScope_;
dataservice = _dataservice_;
}));
Which would you rather write? As importantly, which would you rather *read* ... on your way to the important business of the tests themselves?
### "but globals are bad"
It's a terrible idea to toss variables into the global namespace *in production*.
It'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`?
the 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.
### what is `this`?
Notice the *`this`* argument in
bard.inject(this, '$controller', '$log', '$q', '$rootScope', 'dataservice');
Test 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).
Do 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.
For example, mocha has a "checkLeaks" configuration option that you can turn on like so:
Thus enabled, mocha fails any test that adds variables to the global namespace between the time the test starts and when it finishes.
That'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`.
Fortunately, `inject` can tell mocha to ignore the injected variables if we give it the spec context via `this`.
>Internally `inject` calls another bard function, `addGlobals`. You should call this too if you deliberately extend globals yourself.
**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:
bard.inject('$controller', '$log', '$q', '$rootScope', 'dataservice');
Of 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.
### *inject* a function
The [`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.
The 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:
beforeEach(bard.inject(function($controller, $log, $q, $rootScope, dataservice) {
... do work ..
}));
After the function completes, bard `inject` promotes the injected services to global variables.
## fake services
**Register disabled services that you can spy on.**
Our applications often depend on certain specific services that we like to disable during most of our tests.
Bard offers fake versions of these services. Their methods names begin with the word "fake" and include:
fakeLogger
fakeRouteHelperProvider
fakeRouteProvider
fakeStateProvider
fakeToastr
Look for details in *bard.js*. They all have two features in common:
1. they do nothing
1. their function members are stubbed with [sinon spies](http://sinonjs.org/docs/#spies "sinon spies")
The spies allow a test to assert that one of the service methods was called in the expected manner.
`expect(toastr.error).to.have.been.calledWith('uh oh!');`
You 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:
beforeEach(module('myMod', bard.fakeLogger));
beforeEach(appModule('myMod', bard.fakeLogger));
beforeEach(asyncModule('myMod', bard.fakeLogger));
## log
**The bard `log` method writes messages to `console` when bard debugging is turned on.**
Our 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.
But it can be helpful to sprinkle a little console logging in our code when trying to understand and debug complex tests.
it('should be good', function() {
... tricky stuff that might not work ...
bard.log('we got the goods'); // conditional bard logging
... more tricky stuff ...
expect(good).to.match(/good/);
});
We 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.
Some of bard's own methods call `bard.log`.
## mockService
**Quickly create a mock for any service with spies and return values for every service member.**
It 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.
That 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.
No 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.
Such 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:
beforeEach(function() {
bard.appModule('app.avengers');
bard.inject(this, '$controller', '$q', '$rootScope', 'dataservice');
bard.mockService(dataservice, {
getAvengers: $q.when(avengers),
_default: $q.when([])
});
controller = $controller('Avengers');
$rootScope.$apply();
});
The 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*).
We trust you can see the core ideas in this example:
* you give `mockService` an instance of the real `dataservice` to act as a template.
* the `mockService` replaces every `dataservice` member with a fake implementation.
* all methods are stubbed with [sinon spies](http://sinonjs.org/docs/#spies "sinon spies").
* you can supply return values (such as fulfilled promises) for *specific* methods.
* you determine default return values for the remaining *unspecified* methods.
In 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.
That's easier to write and read than a mock `dataservice` with thirty hand-coded stub methods.
And here are two mocha/chai tests that could follow that setup:
it('controller activation gets avengers', function() {
controller.activate(); // calls `dataservice.getAvengers`
$rootScope.$apply(); // flush pending promises
expect(controller.avengers).to.have.length(avengers.length); // same number as mocked
expect(dataservice.getAvengers).to.have.been.calledOnce; // it's a spy
});
// Call one of the default mock methods which should return
// a promise resolving to an empty array
// Note that the controller would not have called this on its own
it('can call fake `dataservice.getNews`', function() {
dataservice.getNews().then(function(news) {
expect(news).to.have.length(0);
});
$rootScope.$apply(); // flush pending promises
// verify that `getNews` is actually a spy
expect(dataservice.getNews).to.have.been.calledOnce;
});
# Brackets code snippets
Code snippets make test authoring just a little easier. Here
are instructions for loading our snippets into the [Brackets editor](http://brackets.io/ "Brackets editor").
- Open the Brackets Extension manager ( File > Extension manager )
- Install ['Brackets Snippets (by edc)'](https://github.com/chuyik/brackets-snippets)
- Click the light bulb in Brackets' right gutter
- Click `Settings` and then `Import`
- Click `Choose File`
- 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.
- Choose either to `skip` or to `override`
- Click `Start Import`
Now try them in a JavaScript test file
* mocha/jasmine
* `bdescribe` - mocha/jasmine `describe`
* `bit` - `it` test (synchronous)
* `bait` - async `it` test
* `bbeforeEach` - mocha/jasmine `beforeEach`
* `bafterEach` - mocha/jasmine `afterEach`
* `bdone` - tail of a mocha test promise chain: `.then(done, done);`
* chai expectations
* `bexpect` - expect(...).to
* `bcalled` - expect(...).to.have.been.called
* `bequal` - expect(...).to.equal(...)
* `blen` - expect(...).to.have.length(...)
* `bmatch` - expect(...).to.match(/.../i)
* `bprop` - expect(...).to.have.been.property(..., ...)
* `bthrow` - expect function to throw
* bard.js
* `binject` - bard.inject
* `bcinject` - bard.inject for a controller
* `bmodule` - bard.appModule
* `basyncmod` - bard.asyncModule
* `bverify` - bard.verifyNoOutstandingHttpRequests()
* angular.js
* `bapply` - $rootScope.$apply();
* `bwhen` - $httpBackend.when('get', {url}).respond({status}, {data});
* `bflush` - $httpBackend.flush();
* miscellaneous
* `bfn` - generates a function stub
================================================
FILE: bard-ngRouteTester.js
================================================
/* jshint -W117, -W030 */
(function() {
window.bard = window.bard || {};
/**
* Creates the global ngRouteTester function
* to help test ngRoute changes in the DOM
*
* Usage:
*
* beforeEach(function() {
* module('app.module', ngRouteTester(options));
* ... other config ...
* ... ready to roll; inject! ...
* bard.inject('ngRouteTester', ...);
* });
*
* @function ngRouteTester
* @param {Object} [opts]
* @param {Object} [opts.document=document] The document node of the page
* @param {Object} [opts.templateUrl] The template file for the HTML layout of the tester
* @param {Object} [opts.template] The template string for the HTML layout of the tester
* @param {Object} [opts.mockLocationPaths=true] Whether or not to fake the URL change in the browser address bar
*
* Thanks to Matias Niemelä and his ngMidwayTester from
* which most of this code is lifted.
* See http://www.yearofmoo.com/2013/01/full-spectrum-testing-with-angularjs-and-karma.html
*/
window.bard.ngRouteTester = function(opts) {
ngRouteTester.$inject = ['$provide'];
return ngRouteTester;
///////////////////
function ngRouteTester($provide) {
var options = {
document: document
};
angular.extend(options, opts);
configure();
$provide.factory('ngRouteTester', tester);
///////////////////////
var $rootElement,
$timers = [],
$viewContainer,
$terminalElement,
$viewCounter = 0,
doc,
noop = angular.noop;
var viewSelector = 'ng-view, [ng-view], .ng-view, [x-ng-view], [data-ng-view]';
function configure() {
doc = options.document;
$rootElement = angular.element(doc.createElement('div'));
$provide.value('$rootElement', $rootElement);
var mockPaths = options.mockLocationPaths;
if (mockPaths == null ? true : mockPaths) {
$provide.decorator('$location', LocationDecorator);
}
if (options.templateUrl) { getTemplate(); }
if (options.template) {
$rootElement.html(options.template);
var view = angular.element($rootElement[0].querySelector(viewSelector));
$viewContainer = view.parent();
} else {
$viewContainer = angular.element('
');
$rootElement.append($viewContainer);
}
}
LocationDecorator.$inject = ['$delegate', '$rootScope'];
function LocationDecorator($delegate, $rootScope) {
var _path = $delegate.path();
$delegate.path = function(path) {
if (path) {
// sometimes the broadcast triggers a new request for same path
// added this conditional to mitigate risk of this infinite loop
if (_path !== path) {
_path = path;
$rootScope.$broadcast('$locationChangeSuccess', path);
}
return this;
} else {
return _path;
}
};
return $delegate;
}
// get the template from the server synchronously
function getTemplate() {
var request = new XMLHttpRequest();
request.open('GET', options.templateUrl, false);
request.send(null);
if (request.status !== 200) {
throw new Error('ngRouteTester: Unable to download template file');
}
options.template = request.responseText;
}
// ngRouteTester factory
tester.$inject = ['$compile', '$injector', '$rootScope', '$route'];
function tester($compile, $injector, $rootScope, $route) {
bootstrap();
// Arrange for mocha/jasmine to destroy after each test
afterEach && afterEach(destroy);
return {
$injector: $injector,
$rootScope: $rootScope,
$route: $route,
path: path,
rootElement: $rootElement,
until: until,
viewElement : viewElement,
visit : visit
};
///////////////////
function bootstrap() {
$terminalElement = angular.element(
'');
$rootElement.append($terminalElement);
$rootScope.$apply(function() {
$rootElement.data('$injector', $injector);
$compile($rootElement)($rootScope);
angular.element(doc.body).append($rootElement);
});
}
/**
* Removes the $rootElement and clears the module from the page.
* This is done automatically for mocha tests
*
* @method destroy
*/
function destroy() {
angular.forEach($timers, function(timer) {
clearTimeout(timer);
});
var body = angular.element(document.body);
body.removeData();
$rootElement.remove();
$rootScope.$destroy();
}
/**
* @method path
* @return {String} Returns the path of the current route
*/
function path() {
return $injector.get('$location').path();
}
/**
* @method viewElement
* @return {Element} The current element that has ng-view attached to it
*/
function viewElement() {
return angular.element($viewContainer[0].querySelector(viewSelector));
}
/**
* Changes the current route of the page and then fires the callback when the page has loaded
*
* @param {String} path The given path that the current route will be changed to
* @param {function} [callback] The given callback to fire once the view has been fully loaded
* @method visit
*/
function visit(path, callback) {
// wait until view shows up
/* jshint -W106 */
$rootScope.__VIEW_STATUS = ++$viewCounter;
/* jshint +W106 */
until(function() {
return parseInt($terminalElement.attr('status')) >= $viewCounter;
}, function() {
// give it another tick to settle
setTimeout(callback || noop, 0);
});
// tell router to visit the view
var fn = function() {
$injector.get('$location').path(path);
};
$rootScope.$$phase ? fn() : $rootScope.$apply(fn);
}
/**
* Keeps checking an expression until it returns a truthy value and then runs the provided callback
*
* @param {function} exp The given function to poll
* @param {function} callback The given callback to fire once the exp function returns a truthy value
* @method until
*/
function until(exp, callback) {
var timer, delay = 50;
timer = setInterval(function() {
if (exp()) {
clearTimeout(timer);
callback();
}
}, delay);
$timers.push(timer);
}
}
}
};
})();
================================================
FILE: bard.js
================================================
/*jshint -W079, -W117 */
(function() {
var bard = {
$httpBackend: $httpBackendReal,
$q: $qReal,
addGlobals: addGlobals,
appModule: appModule,
assertFail: assertFail,
asyncModule: asyncModule,
debugging: bardDebugging,
fakeLogger: fakeLogger,
fakeRouteHelperProvider: fakeRouteHelperProvider,
fakeRouteProvider: fakeRouteProvider,
fakeStateProvider: fakeStateProvider,
fakeToastr: fakeToastr,
inject: bardInject,
log: bardLog,
mochaRunnerListener: mochaRunnerListener,
mockService: mockService,
replaceAccentChars: replaceAccentChars,
verifyNoOutstandingHttpRequests: verifyNoOutstandingHttpRequests,
wrapWithDone: wrapWithDone
};
var global = (function() { return this; })();
// mocha/jasmine/QUnit fns
var afterEach = global.afterEach || global.teardown;
var beforeEach = global.beforeEach || global.setup;
var clearInject = [];
var currentSpec = null;
var debugging = false;
var logCounter = 0;
var okGlobals = [];
addBindPolyfill();
beforeEach(function bardTopBeforeEach() {
currentSpec = this;
});
afterEach(function bardTopAfterEach() {
currentSpec = null;
bard.log('clearing injected globals: ' + clearInject);
angular.forEach(clearInject, function(name) {
delete global[name];
});
clearInject.length = 0;
okGlobals.length = 0;
});
global.bard = angular.extend(global.bard || {}, bard);
////////////////////////
/*jshint -W101 */
/**
* Replaces the ngMock'ed $httpBackend with the real one from ng thus
* restoring the ability to issue AJAX calls to the backend with $http.
*
* Note that $q remains ngMocked so you must flush $http calls ($rootScope.$digest).
* Use $rootScope.$apply() for this purpose.
*
* Could restore $q with $qReal in which case don't need to flush.
*
* Inspired by this StackOverflow answer:
* http://stackoverflow.com/questions/20864764/e2e-mock-httpbackend-doesnt-actually-passthrough-for-me/26992327?iemail=1&noredirect=1#26992327
*
* Usage:
*
* var myService;
*
* beforeEach(module(bard.$httpBackend, 'app');
*
* beforeEach(inject(function(_myService_) {
* myService = _myService_;
* }));
*
* it('should return valid data', function(done) {
* myService.remoteCall()
* .then(function(data) {
* expect(data).toBeDefined();
* })
* .then(done, done);
*
* // because not using $qReal, must flush the $http and $q queues
* $rootScope.$apply;
* });
*/
/*jshint +W101 */
function $httpBackendReal($provide) {
$provide.provider('$httpBackend', function() {
/*jshint validthis:true */
this.$get = function() {
return angular.injector(['ng']).get('$httpBackend');
};
});
}
/**
* Replaces the ngMock'ed $q with the real one from ng thus
* obviating the need to flush $http and $q queues
* at the expense of ability to control $q timing.
*
* Usage:
*
* var myService;
*
* // Consider: beforeEach(bard.asyncModule('app'));
*
* beforeEach(module(bard.$q, bard.$httpBackend, 'app');
*
* beforeEach(inject(function(_myService_) {
* myService = _myService_;
* }));
*
* it('should return valid data', function(done) {
* myService.remoteCall()
* .then(function(data) {
* expect(data).toBeDefined();
* })
* .then(done, done);
*
* // not need to flush
* });
*/
function $qReal($provide) {
$provide.provider('$q', function() {
/*jshint validthis:true */
this.$get = function() {
return angular.injector(['ng']).get('$q');
};
});
}
/**
* Add names of globals to list of OK globals for this mocha spec
* NB: Call this method ONLY if you're using mocha!
* NB: Turn off browser-sync else mocha detects the browser-sync globals
* like ` ___browserSync___`
*
* usage:
* addGlobals(this, 'foo'); // where `this` is the spec context
* addGlobals(this, 'foo', bar);
* addGlobals.bind(this)('foo', 'bar');
* addGlobals(ctx, ['foo', 'bar']) // where ctx is the spec context
*/
function addGlobals() {
var args = Array.prototype.slice.call(arguments);
var ctx = getCtxFromArgs.bind(this)(args);
var globs = angular.isArray(args[0]) ? args[0] : args;
angular.forEach(globs, function(g) {
if (okGlobals.indexOf(g) === -1) {
okGlobals.push(g);
}
});
// if a mocha test, add the ok globals to it
ctx && ctx.test && ctx.test.globals && ctx.test.globals(okGlobals);
}
/**
* Prepare ngMocked application feature module
* along with faked toastr, routehelper,
* and faked router services.
* Especially useful for controller testing
* Use it as you would the ngMocks#module method
*
* DO NOT USE IF YOU NEED THE REAL ROUTER SERVICES!
* Fall back to `angular.mock.module(...)` or just `module(...)`
*
* Useage:
* beforeEach(bard.appModule('app.avengers'));
*
* Equivalent to:
* beforeEach(angular.mock.module(
* 'app.avengers',
* bard.fakeToastr,
* bard.fakeRouteHelperProvider,
* bard.fakeRouteProvider,
* bard.fakeStateProvider)
* );
*/
function appModule() {
var args = Array.prototype.slice.call(arguments, 0);
args = args.concat(fakeRouteHelperProvider, fakeRouteProvider,
fakeStateProvider, fakeToastr);
return angular.mock.module.apply(angular.mock, args);
}
/**
* Assert a failure in mocha, without condition
*
* Useage:
* assertFail('you are hosed')
*
* Responds:
* AssertionError: you are hosed
* at Object.assertFail (..../test/lib/bard.js:153:15)
* at Context. (.../....spec.js:329:15)
*
* OR JUST THROW the chai.AssertionError and treat this
* as a reminder of how to do it.
*/
function assertFail(message) {
throw new chai.AssertionError(message);
}
/**
* Prepare ngMocked module definition that makes real $http and $q calls
* Also adds fakeLogger to the end of the definition
* Use it as you would the ngMocks#module method
*
* Useage:
* beforeEach(bard.asyncModule('app'));
*
* Equivalent to:
* beforeEach(module('app', bard.$httpBackend, bard.$q, bard.fakeToastr));
*/
function asyncModule() {
var args = Array.prototype.slice.call(arguments, 0);
args = args.concat($httpBackendReal, $qReal, fakeToastr);
// build and return the ngMocked test module
return angular.mock.module.apply(angular.mock, args);
}
/**
* get/set bard debugging flag
*/
function bardDebugging(x) {
if (typeof x !== 'undefined') { debugging = !!x; }
return debugging;
}
/**
* Write to console if bard debugging flag is on
*/
function bardLog(msg) {
if (debugging) {
console.log('---bard (' + (logCounter += 1) + ') ' + msg);
}
}
/**
* inject selected services into the windows object during test
* then remove them when test ends with an `afterEach`.
*
* spares us the repetition of creating common service vars and injecting them
*
* Option: the first argument may be the mocha spec context object (`this`)
* It MUST be `this` if you what to check for mocha global leaks.
* Do NOT supply `this` as the first arg if you're not running mocha specs.
*
* remaining inject arguments may take one of 3 forms :
*
* function - This fn will be passed to ngMocks.inject.
* Annotations extracted after inject does its thing.
* [strings] - same string array you'd use to set fn.$inject
* (...string) - string arguments turned into a string array
*
* usage:
*
* bard.inject(this, ...); // `this` === the spec context
*
* bard.inject(this, '$log', 'dataservice');
* bard.inject(this, ['$log', 'dataservice']);
* bard.inject(this, function($log, dataservice) { ... });
*
*/
function bardInject () {
var args = Array.prototype.slice.call(arguments);
var ctx = getCtxFromArgs.bind(this)(args);
var first = args[0];
if (typeof first === 'function') {
// use ngMocks.inject to execute the func in the arg
angular.mock.inject(first);
args = first.$inject;
if (!args) {
// unfortunately ngMocks.inject only prepares inject.$inject for us
// if using strictDi as of v.1.3.8
// therefore, apply its annotation extraction logic manually
args = getinjectargs(first);
}
}
else if (angular.isArray(first)) {
args = first; // assume is an array of strings
}
// else assume all args are strings
var $injector = currentSpec.$injector;
if (!$injector) {
angular.mock.inject(); // create the injector
$injector = currentSpec.$injector;
}
var names = [];
angular.forEach(args, function(name, ix) {
if (typeof name !== 'string') {
return; // WAT? Only strings allowed. Let's skip it and move on.
}
var value = $injector.get(name);
if (value == null) { return; }
var pathName = name.split('.');
if (pathName.length > 1) {
// name is a path like 'block.foo'. Can't use as identifier
// assume last segment should be identifier name, e.g. 'foo'
name = pathName[pathName.length - 1];
// todo: tolerate component names that are invalid JS identifiers, e.g. 'burning man'
}
global[name] = value;
clearInject.push(name);
names.push(name);
});
bard.addGlobals.bind(ctx)(names);
}
function fakeLogger($provide) {
$provide.value('logger', sinon.stub({
info: function() {},
error: function() {},
warning: function() {},
success: function() {}
}));
}
function fakeToastr($provide) {
$provide.constant('toastr', sinon.stub({
info: function() {},
error: function() {},
warning: function() {},
success: function() {}
}));
}
function fakeRouteHelperProvider($provide) {
$provide.provider('routehelper', function() {
/* jshint validthis:true */
this.config = {
$routeProvider: undefined,
docTitle: 'Testing'
};
this.$get = function() {
return {
configureRoutes: sinon.stub(),
getRoutes: sinon.stub().returns([]),
routeCounts: {
errors: 0,
changes: 0
}
};
};
});
}
function fakeRouteProvider($provide) {
/**
* Stub out the $routeProvider so we avoid
* all routing calls, including the default route
* which runs on every test otherwise.
* Make sure this goes before the inject in the spec.
*
* Optionally set up the fake behavior in your tests by monkey patching
* the faked $route router. For example:
*
* beforeEach(function() {
* // get fake $route router service
* bard.inject(this, '$route');
*
* // plug in fake $route router values for this set of tests
* $route.current = { ... fake values here ... };
* $route.routes = { ... fake values here ... };
* })
*/
$provide.provider('$route', function() {
/* jshint validthis:true */
this.when = sinon.stub();
this.otherwise = sinon.stub();
this.$get = function() {
return {
// current: {}, // fake before each test as needed
// routes: {} // fake before each test as needed
// more? You'll know when it fails :-)
_faked: 'this is the faked $route service'
};
};
});
}
function fakeStateProvider($provide) {
/**
* Stub out the $stateProvider so we avoid
* all routing calls, including the default state
* which runs on every test otherwise.
* Make sure this goes before the inject in the spec.
*
* Optionally set up the fake behavior in your tests by monkey patching
* the faked $state router. For example:
*
* beforeEach(function() {
* // get fake $state router service
* bard.inject(this, '$state');
*
* // plug in fake $state router values for this set of tests
* $state.current = { ... fake values here ... };
* $state.state = { ... fake values here ... };
* })
*/
$provide.provider('$state', function() {
/* jshint validthis:true */
this.state = sinon.stub();
this.$get = function() {
return {
// current: {}, // fake before each test as needed
// state: {} // fake before each test as needed
// more? You'll know when it fails :-)
_faked: 'this is the faked $state service'
};
};
});
$provide.provider('$urlRouter', function() {
/* jshint validthis:true */
this.otherwise = sinon.stub();
this.$get = function() {
return {
// current: {}, // fake before each test as needed
// states: {} // fake before each test as needed
// more? You'll know when it fails :-)
_faked: 'this is the faked $urlRouter service'
};
};
});
}
/**
* Get the spec context from parameters (if there)
* or from `this` (if it is the ctx as a result of `bind`)
*/
function getCtxFromArgs(args) {
var ctx;
var first = args[0];
// heuristic to discover if the first arg is the mocha spec context (`this`)
if (first && first.test) {
// The first arg was the mocha spec context (`this`)
// Get it and strip it from args
ctx = args.shift();
} else if (this.test) {
// alternative: caller can bind bardInject to the spec context
ctx = this;
}
return ctx;
}
/**
* Inspired by Angular; that's how they get the parms for injection
* Todo: no longer used by `injector`. Remove?
*/
function getFnParams(fn) {
var fnText;
var argDecl;
var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
var FN_ARG_SPLIT = /,/;
var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var params = [];
if (fn.length) {
fnText = fn.toString().replace(STRIP_COMMENTS, '');
argDecl = fnText.match(FN_ARGS);
angular.forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
arg.replace(FN_ARG, function(all, underscore, name) {
params.push(name);
});
});
}
return params;
}
function isSpecRunning() { return !!currentSpec; }
/**
* Mocks out a service with sinon stubbed functions
* that return the values specified in the config
*
* If the config value is `undefined`,
* stub the service method with a dummy that doesn't return a value
*
* If the config value is a function, set service property with it
*
* If a service member is a property, not a function,
* set it with the config value
* If a service member name is not a key in config,
* follow the same logic as above to set its members
* using the config._default value (which is `undefined` if omitted)
*
* If there is a config entry that is NOT a member of the service
* add mocked function to the service using the config value
*
* Usage:
* Given this DoWork service:
* {
* doWork1: an async function,
* doWork2: a function,
* doWork3: an async function,
* doWork4: a function,
* isActive: true
* }
*
* Given this config:
* {
* doWork1: $q.when([{name: 'Bob'}, {name: 'Sally'}]),
* doWork2: undefined,
* //doWork3: not in config therefore will get _default value
* doWork4: an alternate doWork4 function
* doWork5: $q.reject('bad boy!')
* isActive: false,
* _default: $q.when([])
* }
*
* Service becomes
* {
* doWork1: a stub returning $q.when([{name: 'Bob'}, {name: 'Sally'}]),
* doWork2: do-nothing stub,
* doWork3: a stub returning $q.when([]),
* doWork4: an alternate doWork4 function,
* doWork5: a stub returning $q.reject('bad boy!'),
* isActive: false,
* }
*/
function mockService(service, config) {
var serviceKeys = [];
for (var key in service) {
serviceKeys.push(key);
}
var configKeys = [];
for (var key in config) {
configKeys.push(key);
}
angular.forEach(serviceKeys, function(key) {
var value = configKeys.indexOf(key) > -1 ?
config[key] : config._default;
if (typeof service[key] === 'function') {
if (typeof value === 'function') {
sinon.stub(service, key, value);
} else {
sinon.stub(service, key, function() {
return value;
});
}
} else {
service[key] = value;
}
});
// for all unused config entries add a sinon stubbed
// async method that returns the config value
angular.forEach(configKeys, function(key) {
if (serviceKeys.indexOf(key) === -1) {
var value = config[key];
if (typeof value === 'function') {
service[key] = value;
} else {
service[key] = sinon.spy(function() {
return value;
});
}
}
});
return service;
}
/**
* Listen to mocha test runner events
* Usage in browser:
* var runner = mocha.run();
* bard.mochaRunnerListener(runner);
*/
function mochaRunnerListener(runner) {
if (!global.mocha) { return; }
if (!runner.ignoreLeaks) {
runner.on('hook end', addOkGlobals);
};
// When checking global leaks with mocha.checkLeaks()
// make sure mocha is aware of bard's okGlobals
function addOkGlobals(hook) {
// HACK: only way I've found so far to ensure that bard added globals
// are always inspected. Using private mocha _allowedGlobals (shhhh!)
if (okGlobals.length && !hook._allowedGlobals) {
hook._allowedGlobals = okGlobals;
}
}
}
// Replaces the accented characters of many European languages w/ unaccented chars
// Use it in JavaScript string sorts where such characters may be encountered
// Matches the default string comparers of most databases.
// Ex: replaceAccentChars(a.Name) < replaceAccentChars(b.Name)
// instead of: a.Name < b.Name
function replaceAccentChars(s) {
var r = s.toLowerCase();
r = r.replace(new RegExp(/[àáâãäå]/g), 'a');
r = r.replace(new RegExp(/æ/g), 'ae');
r = r.replace(new RegExp(/ç/g), 'c');
r = r.replace(new RegExp(/[èéêë]/g), 'e');
r = r.replace(new RegExp(/[ìíîï]/g), 'i');
r = r.replace(new RegExp(/ñ/g), 'n');
r = r.replace(new RegExp(/[òóôõö]/g), 'o');
r = r.replace(new RegExp(/œ/g), 'oe');
r = r.replace(new RegExp(/[ùúûü]/g), 'u');
r = r.replace(new RegExp(/[ýÿ]/g), 'y');
return r;
}
/**
* Assert that there are no outstanding HTTP requests after test is complete
* For use with ngMocks; doesn't work for async server integration tests
*/
function verifyNoOutstandingHttpRequests () {
afterEach(angular.mock.inject(function($httpBackend) {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
}));
}
/**
* Returns a function that execute a callback function
* (typically a fn making asserts) within a try/catch
* The try/catch then calls the ambient "done" function
* in the appropriate way for both success and failure
*
* Useage:
* bard.inject('ngRouteTester', ...); // see bard-ngRouteTester.js
* ...
* // When the DOM is ready, assert got the dashboard view
* ngRouteTester.until(elemIsReady, wrap(hasDashboardView, done));
*/
function wrapWithDone(callback, done) {
return function() {
try {
callback();
done();
} catch (err) {
done(err);
}
};
}
/*
* Phantom.js does not support Function.prototype.bind (at least not before v.2.0
* That's just crazy. Everybody supports bind.
* Read about it here: https://groups.google.com/forum/#!msg/phantomjs/r0hPOmnCUpc/uxusqsl2LNoJ
* This polyfill is copied directly from MDN
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Compatibility
*/
function addBindPolyfill() {
if (Function.prototype.bind) { return; } // already defined
/*jshint freeze: false */
Function.prototype.bind = function (oThis) {
if (typeof this !== 'function') {
// closest thing possible to the ECMAScript 5
// internal IsCallable function
throw new TypeError(
'Function.prototype.bind - what is trying to be bound is not callable');
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
FuncNoOp = function () {},
fBound = function () {
return fToBind.apply(this instanceof FuncNoOp && oThis ? this : oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
FuncNoOp.prototype = this.prototype;
fBound.prototype = new FuncNoOp();
return fBound;
};
}
})();
================================================
FILE: bower.json
================================================
{
"name": "bardjs",
"version": "0.1.10",
"description": "Spec helpers for testing angular v.1.x apps with Mocha, Jasmine or QUnit",
"authors": [
"John Papa",
"Ward Bell"
],
"main": [
"./dist/bard.js",
"./dist/bard-ngRouteTester.js"
],
"license": "MIT",
"homepage": "https://github.com/wardbell/bardjs",
"ignore": [
"node_modules",
"bower_components",
"tests",
"*.html",
"*.js",
".*"
],
"dependencies": {
"angular": ">=1.3.8",
"angular-mocks": ">=1.3.8",
"sinon": "~1.15.0"
},
"devDependencies": {
"chai": "^1.9.1",
"sinon-chai": "^2.5.0"
},
"exportsOverride": {
"sinon": {
"js": "index.js"
}
}
}
================================================
FILE: dist/bard-ngRouteTester.js
================================================
/**
* bardjs - Spec helpers for testing angular v.1.x apps with Mocha, Jasmine or QUnit
* @authors John Papa,Ward Bell
* @version v0.1.10
* @link https://github.com/wardbell/bardjs
* @license MIT
*/
/* jshint -W117, -W030 */
(function() {
window.bard = window.bard || {};
/**
* Creates the global ngRouteTester function
* to help test ngRoute changes in the DOM
*
* Usage:
*
* beforeEach(function() {
* module('app.module', ngRouteTester(options));
* ... other config ...
* ... ready to roll; inject! ...
* bard.inject('ngRouteTester', ...);
* });
*
* @function ngRouteTester
* @param {Object} [opts]
* @param {Object} [opts.document=document] The document node of the page
* @param {Object} [opts.templateUrl] The template file for the HTML layout of the tester
* @param {Object} [opts.template] The template string for the HTML layout of the tester
* @param {Object} [opts.mockLocationPaths=true] Whether or not to fake the URL change in the browser address bar
*
* Thanks to Matias Niemelä and his ngMidwayTester from
* which most of this code is lifted.
* See http://www.yearofmoo.com/2013/01/full-spectrum-testing-with-angularjs-and-karma.html
*/
window.bard.ngRouteTester = function(opts) {
ngRouteTester.$inject = ['$provide'];
return ngRouteTester;
///////////////////
function ngRouteTester($provide) {
var options = {
document: document
};
angular.extend(options, opts);
configure();
$provide.factory('ngRouteTester', tester);
///////////////////////
var $rootElement,
$timers = [],
$viewContainer,
$terminalElement,
$viewCounter = 0,
doc,
noop = angular.noop;
var viewSelector = 'ng-view, [ng-view], .ng-view, [x-ng-view], [data-ng-view]';
function configure() {
doc = options.document;
$rootElement = angular.element(doc.createElement('div'));
$provide.value('$rootElement', $rootElement);
var mockPaths = options.mockLocationPaths;
if (mockPaths == null ? true : mockPaths) {
$provide.decorator('$location', LocationDecorator);
}
if (options.templateUrl) { getTemplate(); }
if (options.template) {
$rootElement.html(options.template);
var view = angular.element($rootElement[0].querySelector(viewSelector));
$viewContainer = view.parent();
} else {
$viewContainer = angular.element('
');
$rootElement.append($viewContainer);
}
}
LocationDecorator.$inject = ['$delegate', '$rootScope'];
function LocationDecorator($delegate, $rootScope) {
var _path = $delegate.path();
$delegate.path = function(path) {
if (path) {
// sometimes the broadcast triggers a new request for same path
// added this conditional to mitigate risk of this infinite loop
if (_path !== path) {
_path = path;
$rootScope.$broadcast('$locationChangeSuccess', path);
}
return this;
} else {
return _path;
}
};
return $delegate;
}
// get the template from the server synchronously
function getTemplate() {
var request = new XMLHttpRequest();
request.open('GET', options.templateUrl, false);
request.send(null);
if (request.status !== 200) {
throw new Error('ngRouteTester: Unable to download template file');
}
options.template = request.responseText;
}
// ngRouteTester factory
tester.$inject = ['$compile', '$injector', '$rootScope', '$route'];
function tester($compile, $injector, $rootScope, $route) {
bootstrap();
// Arrange for mocha/jasmine to destroy after each test
afterEach && afterEach(destroy);
return {
$injector: $injector,
$rootScope: $rootScope,
$route: $route,
path: path,
rootElement: $rootElement,
until: until,
viewElement : viewElement,
visit : visit
};
///////////////////
function bootstrap() {
$terminalElement = angular.element(
'');
$rootElement.append($terminalElement);
$rootScope.$apply(function() {
$rootElement.data('$injector', $injector);
$compile($rootElement)($rootScope);
angular.element(doc.body).append($rootElement);
});
}
/**
* Removes the $rootElement and clears the module from the page.
* This is done automatically for mocha tests
*
* @method destroy
*/
function destroy() {
angular.forEach($timers, function(timer) {
clearTimeout(timer);
});
var body = angular.element(document.body);
body.removeData();
$rootElement.remove();
$rootScope.$destroy();
}
/**
* @method path
* @return {String} Returns the path of the current route
*/
function path() {
return $injector.get('$location').path();
}
/**
* @method viewElement
* @return {Element} The current element that has ng-view attached to it
*/
function viewElement() {
return angular.element($viewContainer[0].querySelector(viewSelector));
}
/**
* Changes the current route of the page and then fires the callback when the page has loaded
*
* @param {String} path The given path that the current route will be changed to
* @param {function} [callback] The given callback to fire once the view has been fully loaded
* @method visit
*/
function visit(path, callback) {
// wait until view shows up
/* jshint -W106 */
$rootScope.__VIEW_STATUS = ++$viewCounter;
/* jshint +W106 */
until(function() {
return parseInt($terminalElement.attr('status')) >= $viewCounter;
}, function() {
// give it another tick to settle
setTimeout(callback || noop, 0);
});
// tell router to visit the view
var fn = function() {
$injector.get('$location').path(path);
};
$rootScope.$$phase ? fn() : $rootScope.$apply(fn);
}
/**
* Keeps checking an expression until it returns a truthy value and then runs the provided callback
*
* @param {function} exp The given function to poll
* @param {function} callback The given callback to fire once the exp function returns a truthy value
* @method until
*/
function until(exp, callback) {
var timer, delay = 50;
timer = setInterval(function() {
if (exp()) {
clearTimeout(timer);
callback();
}
}, delay);
$timers.push(timer);
}
}
}
};
})();
================================================
FILE: dist/bard.js
================================================
/**
* bardjs - Spec helpers for testing angular v.1.x apps with Mocha, Jasmine or QUnit
* @authors John Papa,Ward Bell
* @version v0.1.10
* @link https://github.com/wardbell/bardjs
* @license MIT
*/
/*jshint -W079, -W117 */
(function() {
var bard = {
$httpBackend: $httpBackendReal,
$q: $qReal,
addGlobals: addGlobals,
appModule: appModule,
assertFail: assertFail,
asyncModule: asyncModule,
debugging: bardDebugging,
fakeLogger: fakeLogger,
fakeRouteHelperProvider: fakeRouteHelperProvider,
fakeRouteProvider: fakeRouteProvider,
fakeStateProvider: fakeStateProvider,
fakeToastr: fakeToastr,
inject: bardInject,
log: bardLog,
mochaRunnerListener: mochaRunnerListener,
mockService: mockService,
replaceAccentChars: replaceAccentChars,
verifyNoOutstandingHttpRequests: verifyNoOutstandingHttpRequests,
wrapWithDone: wrapWithDone
};
var global = (function() { return this; })();
// mocha/jasmine/QUnit fns
var afterEach = global.afterEach || global.teardown;
var beforeEach = global.beforeEach || global.setup;
var clearInject = [];
var currentSpec = null;
var debugging = false;
var logCounter = 0;
var okGlobals = [];
addBindPolyfill();
beforeEach(function bardTopBeforeEach() {
currentSpec = this;
});
afterEach(function bardTopAfterEach() {
currentSpec = null;
bard.log('clearing injected globals: ' + clearInject);
angular.forEach(clearInject, function(name) {
delete global[name];
});
clearInject.length = 0;
okGlobals.length = 0;
});
global.bard = angular.extend(global.bard || {}, bard);
////////////////////////
/*jshint -W101 */
/**
* Replaces the ngMock'ed $httpBackend with the real one from ng thus
* restoring the ability to issue AJAX calls to the backend with $http.
*
* Note that $q remains ngMocked so you must flush $http calls ($rootScope.$digest).
* Use $rootScope.$apply() for this purpose.
*
* Could restore $q with $qReal in which case don't need to flush.
*
* Inspired by this StackOverflow answer:
* http://stackoverflow.com/questions/20864764/e2e-mock-httpbackend-doesnt-actually-passthrough-for-me/26992327?iemail=1&noredirect=1#26992327
*
* Usage:
*
* var myService;
*
* beforeEach(module(bard.$httpBackend, 'app');
*
* beforeEach(inject(function(_myService_) {
* myService = _myService_;
* }));
*
* it('should return valid data', function(done) {
* myService.remoteCall()
* .then(function(data) {
* expect(data).toBeDefined();
* })
* .then(done, done);
*
* // because not using $qReal, must flush the $http and $q queues
* $rootScope.$apply;
* });
*/
/*jshint +W101 */
function $httpBackendReal($provide) {
$provide.provider('$httpBackend', function() {
/*jshint validthis:true */
this.$get = function() {
return angular.injector(['ng']).get('$httpBackend');
};
});
}
/**
* Replaces the ngMock'ed $q with the real one from ng thus
* obviating the need to flush $http and $q queues
* at the expense of ability to control $q timing.
*
* Usage:
*
* var myService;
*
* // Consider: beforeEach(bard.asyncModule('app'));
*
* beforeEach(module(bard.$q, bard.$httpBackend, 'app');
*
* beforeEach(inject(function(_myService_) {
* myService = _myService_;
* }));
*
* it('should return valid data', function(done) {
* myService.remoteCall()
* .then(function(data) {
* expect(data).toBeDefined();
* })
* .then(done, done);
*
* // not need to flush
* });
*/
function $qReal($provide) {
$provide.provider('$q', function() {
/*jshint validthis:true */
this.$get = function() {
return angular.injector(['ng']).get('$q');
};
});
}
/**
* Add names of globals to list of OK globals for this mocha spec
* NB: Call this method ONLY if you're using mocha!
* NB: Turn off browser-sync else mocha detects the browser-sync globals
* like ` ___browserSync___`
*
* usage:
* addGlobals(this, 'foo'); // where `this` is the spec context
* addGlobals(this, 'foo', bar);
* addGlobals.bind(this)('foo', 'bar');
* addGlobals(ctx, ['foo', 'bar']) // where ctx is the spec context
*/
function addGlobals() {
var args = Array.prototype.slice.call(arguments);
var ctx = getCtxFromArgs.bind(this)(args);
var globs = angular.isArray(args[0]) ? args[0] : args;
angular.forEach(globs, function(g) {
if (okGlobals.indexOf(g) === -1) {
okGlobals.push(g);
}
});
// if a mocha test, add the ok globals to it
ctx && ctx.test && ctx.test.globals && ctx.test.globals(okGlobals);
}
/**
* Prepare ngMocked application feature module
* along with faked toastr, routehelper,
* and faked router services.
* Especially useful for controller testing
* Use it as you would the ngMocks#module method
*
* DO NOT USE IF YOU NEED THE REAL ROUTER SERVICES!
* Fall back to `angular.mock.module(...)` or just `module(...)`
*
* Useage:
* beforeEach(bard.appModule('app.avengers'));
*
* Equivalent to:
* beforeEach(angular.mock.module(
* 'app.avengers',
* bard.fakeToastr,
* bard.fakeRouteHelperProvider,
* bard.fakeRouteProvider,
* bard.fakeStateProvider)
* );
*/
function appModule() {
var args = Array.prototype.slice.call(arguments, 0);
args = args.concat(fakeRouteHelperProvider, fakeRouteProvider,
fakeStateProvider, fakeToastr);
return angular.mock.module.apply(angular.mock, args);
}
/**
* Assert a failure in mocha, without condition
*
* Useage:
* assertFail('you are hosed')
*
* Responds:
* AssertionError: you are hosed
* at Object.assertFail (..../test/lib/bard.js:153:15)
* at Context. (.../....spec.js:329:15)
*
* OR JUST THROW the chai.AssertionError and treat this
* as a reminder of how to do it.
*/
function assertFail(message) {
throw new chai.AssertionError(message);
}
/**
* Prepare ngMocked module definition that makes real $http and $q calls
* Also adds fakeLogger to the end of the definition
* Use it as you would the ngMocks#module method
*
* Useage:
* beforeEach(bard.asyncModule('app'));
*
* Equivalent to:
* beforeEach(module('app', bard.$httpBackend, bard.$q, bard.fakeToastr));
*/
function asyncModule() {
var args = Array.prototype.slice.call(arguments, 0);
args = args.concat($httpBackendReal, $qReal, fakeToastr);
// build and return the ngMocked test module
return angular.mock.module.apply(angular.mock, args);
}
/**
* get/set bard debugging flag
*/
function bardDebugging(x) {
if (typeof x !== 'undefined') { debugging = !!x; }
return debugging;
}
/**
* Write to console if bard debugging flag is on
*/
function bardLog(msg) {
if (debugging) {
console.log('---bard (' + (logCounter += 1) + ') ' + msg);
}
}
/**
* inject selected services into the windows object during test
* then remove them when test ends with an `afterEach`.
*
* spares us the repetition of creating common service vars and injecting them
*
* Option: the first argument may be the mocha spec context object (`this`)
* It MUST be `this` if you what to check for mocha global leaks.
* Do NOT supply `this` as the first arg if you're not running mocha specs.
*
* remaining inject arguments may take one of 3 forms :
*
* function - This fn will be passed to ngMocks.inject.
* Annotations extracted after inject does its thing.
* [strings] - same string array you'd use to set fn.$inject
* (...string) - string arguments turned into a string array
*
* usage:
*
* bard.inject(this, ...); // `this` === the spec context
*
* bard.inject(this, '$log', 'dataservice');
* bard.inject(this, ['$log', 'dataservice']);
* bard.inject(this, function($log, dataservice) { ... });
*
*/
function bardInject () {
var args = Array.prototype.slice.call(arguments);
var ctx = getCtxFromArgs.bind(this)(args);
var first = args[0];
if (typeof first === 'function') {
// use ngMocks.inject to execute the func in the arg
angular.mock.inject(first);
args = first.$inject;
if (!args) {
// unfortunately ngMocks.inject only prepares inject.$inject for us
// if using strictDi as of v.1.3.8
// therefore, apply its annotation extraction logic manually
args = getinjectargs(first);
}
}
else if (angular.isArray(first)) {
args = first; // assume is an array of strings
}
// else assume all args are strings
var $injector = currentSpec.$injector;
if (!$injector) {
angular.mock.inject(); // create the injector
$injector = currentSpec.$injector;
}
var names = [];
angular.forEach(args, function(name, ix) {
if (typeof name !== 'string') {
return; // WAT? Only strings allowed. Let's skip it and move on.
}
var value = $injector.get(name);
if (value == null) { return; }
var pathName = name.split('.');
if (pathName.length > 1) {
// name is a path like 'block.foo'. Can't use as identifier
// assume last segment should be identifier name, e.g. 'foo'
name = pathName[pathName.length - 1];
// todo: tolerate component names that are invalid JS identifiers, e.g. 'burning man'
}
global[name] = value;
clearInject.push(name);
names.push(name);
});
bard.addGlobals.bind(ctx)(names);
}
function fakeLogger($provide) {
$provide.value('logger', sinon.stub({
info: function() {},
error: function() {},
warning: function() {},
success: function() {}
}));
}
function fakeToastr($provide) {
$provide.constant('toastr', sinon.stub({
info: function() {},
error: function() {},
warning: function() {},
success: function() {}
}));
}
function fakeRouteHelperProvider($provide) {
$provide.provider('routehelper', function() {
/* jshint validthis:true */
this.config = {
$routeProvider: undefined,
docTitle: 'Testing'
};
this.$get = function() {
return {
configureRoutes: sinon.stub(),
getRoutes: sinon.stub().returns([]),
routeCounts: {
errors: 0,
changes: 0
}
};
};
});
}
function fakeRouteProvider($provide) {
/**
* Stub out the $routeProvider so we avoid
* all routing calls, including the default route
* which runs on every test otherwise.
* Make sure this goes before the inject in the spec.
*
* Optionally set up the fake behavior in your tests by monkey patching
* the faked $route router. For example:
*
* beforeEach(function() {
* // get fake $route router service
* bard.inject(this, '$route');
*
* // plug in fake $route router values for this set of tests
* $route.current = { ... fake values here ... };
* $route.routes = { ... fake values here ... };
* })
*/
$provide.provider('$route', function() {
/* jshint validthis:true */
this.when = sinon.stub();
this.otherwise = sinon.stub();
this.$get = function() {
return {
// current: {}, // fake before each test as needed
// routes: {} // fake before each test as needed
// more? You'll know when it fails :-)
_faked: 'this is the faked $route service'
};
};
});
}
function fakeStateProvider($provide) {
/**
* Stub out the $stateProvider so we avoid
* all routing calls, including the default state
* which runs on every test otherwise.
* Make sure this goes before the inject in the spec.
*
* Optionally set up the fake behavior in your tests by monkey patching
* the faked $state router. For example:
*
* beforeEach(function() {
* // get fake $state router service
* bard.inject(this, '$state');
*
* // plug in fake $state router values for this set of tests
* $state.current = { ... fake values here ... };
* $state.state = { ... fake values here ... };
* })
*/
$provide.provider('$state', function() {
/* jshint validthis:true */
this.state = sinon.stub();
this.$get = function() {
return {
// current: {}, // fake before each test as needed
// state: {} // fake before each test as needed
// more? You'll know when it fails :-)
_faked: 'this is the faked $state service'
};
};
});
$provide.provider('$urlRouter', function() {
/* jshint validthis:true */
this.otherwise = sinon.stub();
this.$get = function() {
return {
// current: {}, // fake before each test as needed
// states: {} // fake before each test as needed
// more? You'll know when it fails :-)
_faked: 'this is the faked $urlRouter service'
};
};
});
}
/**
* Get the spec context from parameters (if there)
* or from `this` (if it is the ctx as a result of `bind`)
*/
function getCtxFromArgs(args) {
var ctx;
var first = args[0];
// heuristic to discover if the first arg is the mocha spec context (`this`)
if (first && first.test) {
// The first arg was the mocha spec context (`this`)
// Get it and strip it from args
ctx = args.shift();
} else if (this.test) {
// alternative: caller can bind bardInject to the spec context
ctx = this;
}
return ctx;
}
/**
* Inspired by Angular; that's how they get the parms for injection
* Todo: no longer used by `injector`. Remove?
*/
function getFnParams(fn) {
var fnText;
var argDecl;
var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
var FN_ARG_SPLIT = /,/;
var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var params = [];
if (fn.length) {
fnText = fn.toString().replace(STRIP_COMMENTS, '');
argDecl = fnText.match(FN_ARGS);
angular.forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
arg.replace(FN_ARG, function(all, underscore, name) {
params.push(name);
});
});
}
return params;
}
function isSpecRunning() { return !!currentSpec; }
/**
* Mocks out a service with sinon stubbed functions
* that return the values specified in the config
*
* If the config value is `undefined`,
* stub the service method with a dummy that doesn't return a value
*
* If the config value is a function, set service property with it
*
* If a service member is a property, not a function,
* set it with the config value
* If a service member name is not a key in config,
* follow the same logic as above to set its members
* using the config._default value (which is `undefined` if omitted)
*
* If there is a config entry that is NOT a member of the service
* add mocked function to the service using the config value
*
* Usage:
* Given this DoWork service:
* {
* doWork1: an async function,
* doWork2: a function,
* doWork3: an async function,
* doWork4: a function,
* isActive: true
* }
*
* Given this config:
* {
* doWork1: $q.when([{name: 'Bob'}, {name: 'Sally'}]),
* doWork2: undefined,
* //doWork3: not in config therefore will get _default value
* doWork4: an alternate doWork4 function
* doWork5: $q.reject('bad boy!')
* isActive: false,
* _default: $q.when([])
* }
*
* Service becomes
* {
* doWork1: a stub returning $q.when([{name: 'Bob'}, {name: 'Sally'}]),
* doWork2: do-nothing stub,
* doWork3: a stub returning $q.when([]),
* doWork4: an alternate doWork4 function,
* doWork5: a stub returning $q.reject('bad boy!'),
* isActive: false,
* }
*/
function mockService(service, config) {
var serviceKeys = [];
for (var key in service) {
serviceKeys.push(key);
}
var configKeys = [];
for (var key in config) {
configKeys.push(key);
}
angular.forEach(serviceKeys, function(key) {
var value = configKeys.indexOf(key) > -1 ?
config[key] : config._default;
if (typeof service[key] === 'function') {
if (typeof value === 'function') {
service[key] = value;
} else {
sinon.stub(service, key, function() {
return value;
});
}
} else {
service[key] = value;
}
});
// for all unused config entries add a sinon stubbed
// async method that returns the config value
angular.forEach(configKeys, function(key) {
if (serviceKeys.indexOf(key) === -1) {
var value = config[key];
if (typeof value === 'function') {
service[key] = value;
} else {
service[key] = sinon.spy(function() {
return value;
});
}
}
});
return service;
}
/**
* Listen to mocha test runner events
* Usage in browser:
* var runner = mocha.run();
* bard.mochaRunnerListener(runner);
*/
function mochaRunnerListener(runner) {
if (!global.mocha) { return; }
if (!runner.ignoreLeaks) {
runner.on('hook end', addOkGlobals);
};
// When checking global leaks with mocha.checkLeaks()
// make sure mocha is aware of bard's okGlobals
function addOkGlobals(hook) {
// HACK: only way I've found so far to ensure that bard added globals
// are always inspected. Using private mocha _allowedGlobals (shhhh!)
if (okGlobals.length && !hook._allowedGlobals) {
hook._allowedGlobals = okGlobals;
}
}
}
// Replaces the accented characters of many European languages w/ unaccented chars
// Use it in JavaScript string sorts where such characters may be encountered
// Matches the default string comparers of most databases.
// Ex: replaceAccentChars(a.Name) < replaceAccentChars(b.Name)
// instead of: a.Name < b.Name
function replaceAccentChars(s) {
var r = s.toLowerCase();
r = r.replace(new RegExp(/[àáâãäå]/g), 'a');
r = r.replace(new RegExp(/æ/g), 'ae');
r = r.replace(new RegExp(/ç/g), 'c');
r = r.replace(new RegExp(/[èéêë]/g), 'e');
r = r.replace(new RegExp(/[ìíîï]/g), 'i');
r = r.replace(new RegExp(/ñ/g), 'n');
r = r.replace(new RegExp(/[òóôõö]/g), 'o');
r = r.replace(new RegExp(/œ/g), 'oe');
r = r.replace(new RegExp(/[ùúûü]/g), 'u');
r = r.replace(new RegExp(/[ýÿ]/g), 'y');
return r;
}
/**
* Assert that there are no outstanding HTTP requests after test is complete
* For use with ngMocks; doesn't work for async server integration tests
*/
function verifyNoOutstandingHttpRequests () {
afterEach(angular.mock.inject(function($httpBackend) {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
}));
}
/**
* Returns a function that execute a callback function
* (typically a fn making asserts) within a try/catch
* The try/catch then calls the ambient "done" function
* in the appropriate way for both success and failure
*
* Useage:
* bard.inject('ngRouteTester', ...); // see bard-ngRouteTester.js
* ...
* // When the DOM is ready, assert got the dashboard view
* ngRouteTester.until(elemIsReady, wrap(hasDashboardView, done));
*/
function wrapWithDone(callback, done) {
return function() {
try {
callback();
done();
} catch (err) {
done(err);
}
};
}
/*
* Phantom.js does not support Function.prototype.bind (at least not before v.2.0
* That's just crazy. Everybody supports bind.
* Read about it here: https://groups.google.com/forum/#!msg/phantomjs/r0hPOmnCUpc/uxusqsl2LNoJ
* This polyfill is copied directly from MDN
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Compatibility
*/
function addBindPolyfill() {
if (Function.prototype.bind) { return; } // already defined
/*jshint freeze: false */
Function.prototype.bind = function (oThis) {
if (typeof this !== 'function') {
// closest thing possible to the ECMAScript 5
// internal IsCallable function
throw new TypeError(
'Function.prototype.bind - what is trying to be bound is not callable');
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
FuncNoOp = function () {},
fBound = function () {
return fToBind.apply(this instanceof FuncNoOp && oThis ? this : oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
FuncNoOp.prototype = this.prototype;
fBound.prototype = new FuncNoOp();
return fBound;
};
}
})();
================================================
FILE: gulp.config.js
================================================
module.exports = function() {
var root = './';
var service = {
getConfig: getConfig
};
return service;
function getConfig() {
var config = {
specs: ['./tests/**/*.spec.js'],
js: [
'./bard.js',
'./bard-ngRouteTester.js'
],
packages: [
'./package.json',
'./bower.json'
],
build: './dist/',
report: './report/',
root: root
};
return config;
}
};
================================================
FILE: gulpfile.js
================================================
var gulp = require('gulp');
var args = require('yargs').argv;
var config = require('./gulp.config')().getConfig();
var del = require('del');
var glob = require('glob');
var _ = require('lodash');
var path = require('path');
var $ = require('gulp-load-plugins')({lazy: true});
var colors = $.util.colors;
var env = $.util.env;
/**
* List the available gulp tasks
*/
gulp.task('help', $.taskListing);
gulp.task('default', ['help']);
/**
* Lint the code, create coverage report, and a visualizer
* @return {Stream}
*/
gulp.task('vet', function() {
log('Analyzing source with JSHint and JSCS');
return gulp
.src(config.js)
.pipe($.if(env.verbose, $.print()))
.pipe($.jshint.reporter('jshint-stylish'))
.pipe($.jscs());
});
/**
* Bump the version
* --type=pre will bump the prerelease version *.*.*-x
* --type=patch or no flag will bump the patch version *.*.x
* --type=minor will bump the minor version *.x.*
* --type=major will bump the major version x.*.*
* --version=1.2.3 will bump to a specific version and ignore other flags
*/
gulp.task('bump', function() {
var msg = 'Bumping versions';
var type = args.type;
var version = args.ver;
var options = {};
if (version) {
options.version = version;
msg += ' to ' + version;
} else {
options.type = type;
msg += ' for a ' + type;
}
log(msg);
return gulp
.src(config.packages)
.pipe($.print())
.pipe($.bump(options))
.pipe(gulp.dest(config.root));
});
/**
* Build everything
*/
gulp.task('build', ['clean'], function(done) {
log('Optimizing the js, css, and html');
var stream = gulp
.src(config.js)
.pipe(getHeader())
.pipe(gulp.dest(config.build))
.pipe($.uglify())
.pipe(getHeader())
.pipe($.rename('bard.min.js'))
.pipe(gulp.dest(config.build))
.on('end', success)
.on('error', error);
function error(err) {
log(err);
done(err);
}
function success() {
var msg = {
title: 'gulp build',
message: 'Deployed to the dist folder'
};
log(msg);
notify(msg);
done();
}
});
/**
* Remove all files from the build, temp, and reports folders
* @param {Function} done - callback when complete
*/
gulp.task('clean', function(done) {
var delconfig = [].concat(config.build, config.report);
log('Cleaning: ' + $.util.colors.blue(delconfig));
del(delconfig, done);
});
/**
* Delete all files in a given path
* @param {Array} path - array of paths to delete
* @param {Function} done - callback when complete
*/
function clean(path, done) {
log('Cleaning: ' + $.util.colors.blue(path));
del(path, done);
}
/**
* Formatter for bytediff to display the size changes after processing
* @param {Object} data - byte data
* @return {String} Difference in bytes, formatted
*/
function bytediffFormatter(data) {
var difference = (data.savings > 0) ? ' smaller.' : ' larger.';
return data.fileName + ' went from ' +
(data.startSize / 1000).toFixed(2) + ' kB to ' +
(data.endSize / 1000).toFixed(2) + ' kB and is ' +
formatPercent(1 - data.percent, 2) + '%' + difference;
}
/**
* Format a number as a percentage
* @param {Number} num Number to format as a percent
* @param {Number} precision Precision of the decimal
* @return {String} Formatted perentage
*/
function formatPercent(num, precision) {
return (num * 100).toFixed(precision);
}
/**
* Format and return the header for files
* @return {String} Formatted file header
*/
function getHeader() {
var pkg = require('./package.json');
var template = ['/**',
' * <%= pkg.name %> - <%= pkg.description %>',
' * @authors <%= pkg.authors %>',
' * @version v<%= pkg.version %>',
' * @link <%= pkg.homepage %>',
' * @license <%= pkg.license %>',
' */',
''
].join('\n');
return $.header(template, {
pkg: pkg
});
}
/**
* Log a message or series of messages using chalk's blue color.
* Can pass in a string, object or array.
*/
function log(msg) {
if (typeof(msg) === 'object') {
for (var item in msg) {
if (msg.hasOwnProperty(item)) {
$.util.log($.util.colors.blue(msg[item]));
}
}
} else {
$.util.log($.util.colors.blue(msg));
}
}
/**
* Show OS level notification using node-notifier
*/
function notify(options) {
var notifier = require('node-notifier');
var notifyOptions = {
sound: 'Bottle',
contentImage: path.join(__dirname, 'gulp.png'),
icon: path.join(__dirname, 'gulp.png')
};
_.assign(notifyOptions, options);
notifier.notify(notifyOptions);
}
================================================
FILE: index.html
================================================
bardjs tests