Sails + Angular + Jasmine - angularjs

I use SailsJS for backend and Angular for front End. So far, they work well. SailsJS backend logic has tests in Mocha. I am trying to add some tests for front end Angular.
Angular's documentation on testing is cryptic to me. After reading its documentation for quite some time, I still have no idea about where to start.
1) Where should I put the unit test code for Angular in a SailsJS project? Now Angular code lives under assets/js. Should I put the test under the same directory, like the following?
assets/js/MyAngularCode.js
assets/js/MyAngularCode_test.js
MyAngularCode.js
(function(){
var myApp = angular.module('myApp', []);
myApp.controller('FirstController', [$scope, function($scope){
//blah blah
}]);
})();
What should I write in MyAngularCode_test.js to test any logic in FirstController?
2) How to run Jasmine tests for any given file directory structure in a SailsJS + Angular project?
How to make "Jasmine init" and "Jasmine" work in such a project. I assume need a Jasmine.json file. But where should it be?
3) For example, I have a file,
FirstTest.js
'use strict';
describe("A suite", function() {
beforeEach(angular.mock.module('myApp'));
it("contains spec with an expectation", function() {
expect(true).toBe(true);
});
});
Where should I put it and what should I do so it will not show the following error
ReferenceError: angular is not defined

Since you want just any opinion...
You can use yeoman for scaffolding; this will help you create pages and directory structure.
Use generator-angular since you are working with angular
yo angular:controller foobar will create files for your controller as well as the test files.
It will create a package.json with a test command (grunt test) which works out of the box.
There is a tutorial here: http://yeoman.io/codelab.html

Just clone this github repo, it's a blank app and uses Angular for the front-end https://github.com/sgress454/angular-on-sails

Related

Unable to Inject $httpBackend

I am using Angular 1.5 to write mocked services for my project by following this little example: https://embed.plnkr.co/qsmx8RUmQlXKkeXny7Rx/
This is a simple code that I have written so far:
function() {
'use strict';
angular.module('agMock', ['ag', 'ngMockE2E'])
.run(function($httpBackend) {
$httpBackend.whenGET('https://localhost:8080/api/users')
.respond({user: 'fooBarBaz', roles: ['admin', 'user']});
});
})();
'ag' is the parent module of my project for which I am going to write mocks. When I try and run this, I get the error saying 'unknown provider: $httpBackend' although I have included angular.mocks library. Can anybody take a guess what can go wrong?
So I figured out why was I getting this error. The project in which I was getting this error uses gulp to inject dependencies and generate index.html files for dev and mocked environment. In the template index.html file, I had the main parent module, "äg" referenced in the ng-app.
I skipped the part where I had to substitute "agMock" instead of "ag" in the ng-app while generating mocked index. So this was the problem. Phew.

Usage of spec.js file in AngularJS

This might sound a stupid question, but I want to know its answer. What is the spec.js file in AngularJS and what is its use? Is it used for testing purpose?
EDIT- Below is the code of file phone-detail.component.spec.js
'use strict';
describe('phoneDetail', function() {
// Load the module that contains the `phoneDetail` component before each test
beforeEach(module('phoneDetail'));
// Test the controller
describe('PhoneDetailController', function() {
var $httpBackend, ctrl;
var xyzPhoneData = {
name: 'phone xyz',
images: ['image/url1.png', 'image/url2.png']
};
beforeEach(inject(function($componentController, _$httpBackend_, $routeParams) {
$httpBackend = _$httpBackend_;
$httpBackend.expectGET('phones/xyz.json').respond(xyzPhoneData);
$routeParams.phoneId = 'xyz';
ctrl = $componentController('phoneDetail');
}));
it('should fetch the phone details', function() {
jasmine.addCustomEqualityTester(angular.equals);
expect(ctrl.phone).toEqual({});
$httpBackend.flush();
expect(ctrl.phone).toEqual(xyzPhoneData);
});
});
});
Use of spec.js is for writing you unit test cases for your angular application.
We write test cases in angular using Jasmine & Karma.
Jasmine is a Behavior Driven Development testing framework for JavaScript. It does not rely on browsers, DOM, or any JavaScript framework. Thus it's suited for websites, Node.js projects, or anywhere that JavaScript can run.
https://github.com/jasmine/jasmine
Karma is essentially a tool which spawns a web server that executes source code against test code for each of the browsers connected. The results of each test against each browser are examined and displayed via the command line to the developer such that they can see which browsers and tests passed or failed.
https://karma-runner.github.io/1.0/index.html
Question - What is the spec.js file in AngularJS ?
Answer - AngularJS uses Jasmine as a testing framework and tests written in Jasmine are called specs. Filename written related to Jasmine must be .spec.ts, the filename extension convention is adhered by configuration of
karma( the test runner tool ).
Question - what is its use? Is it used for testing purpose?
Answer - Karma the test runner gets the specifications for testing from this file. yes, it is used for testing :)
Reference https://angular.io/guide/testing

Where should I use $templateCache?

I want to use $templateCache service to add some html into the cache. In Angular documentation example, it only shows the case of using it in run:
var myApp = angular.module('myApp', []);
myApp.run(function($templateCache) {
$templateCache.put('templateId.html', 'This is the content of the template');
});
However, when I am trying to add some templates through myApp config, there seems to be injector error. Is there a way to use templateCache not in RUN?
Thanks
run is the correct place to use the $templateCache. Since $templateCache is a service, it's not accessible in the configuration phase, because it hasn't been created yet. config is used to configure services (like $templateCache) using their providers. You can only inject providers to config.
My opinion is that, most of the time, you shouldn't be writing code that accesses $templateCache directly at all. What you should be doing is using a build system such as gulp and a plugin such as gulp-angular-templatecache.
Then your templates are simply a bunch of .html files, your editor recognises them as html and does the appropriate linting while you edit, and all you have to do is ensure your app declares a dependency on the template module.
So the code you gave above would become:
var myApp = angular.module('myApp', ['myappTemplates']);
and the use of $templateCache inside .run() is pushed down to automatically generated code that you never see.

AngularJS unit testing. HttpBackend

I have AngularJS app with unit tests covering it. I added one more http request in .run part of application which checking user authentication. Now about 60% of my tests fails because they found 'unexpected http request'. Even directives tests are fail. How can I avoid running this request in tests? How can I easily mock this request in all tests? Im trying to not to put httpBackend.expect('GET', 'URL') to each test - that's too much work.
Testing with Jasmine + Karma
Thanks. I can give more details if needed.
There are a few ways to do this:
1.) Include a beforeEach that Tim Castelijns suggested but for every spec file
2.) Include the beforeEach in a separate file called app-mocks.js & include in your karma.conf.js (I'm guessing you have one).
karma.conf.js
files: [
'location/of/app-mocks.js',
'src/app/**/*.js'
],
app-mocks.js
(function () {
'use strict';
beforeEach(inject(function ($httpBackend) {
$httpBackend.whenGET('blahblahblah.com/cat/:id/food').respond('');
}));
})();
3.) Separate out user authentication logic from the core app and create an $http wrapper service (suggested). Thus you could have (simplified example):
app.js
angular.module('myApp', ['myApp.services']);
user-service.js
angular.module('myApp.services', [])
.factory('User', function ($http) {
function authenticate() {
// authenticate user
}
return {
authenticate: authenticate
};
});
and same for your directives, controllers, etc. This way, you can unit test all of your components in isolation without having to worry about intertwined logic that is actually specific to one type of functionality. Also, when you do test core app functionality, you can just mock or spy on your User service. In your spec files you would inject only the module & functionality you are testing. So instead of injecting your entire core app module, you would:
To test services
beforeEach(module('myApp.services'));
To test directives
beforeEach(module('myApp.directives'));
etc.
Of Note: When your application starts to get big, I would consider organizing your app components based on feature rather than by type as this example above does.
You can use a beforeEach block to define a call that all tests should expect
var httpBackend;
beforeEach(inject(function(_$httpBackend_) {
httpBackend = _$httpBackend_;
httpBackend.expect('GET', 'URL').respond('');
}
Note the .respond('') I added, an expect call needs this, see the documentation if you want to know why.
This beforeEach functionality comes with the widely used jasmine testing framework.

Using Karma to scenario test an AngularJS controller?

Here is what I have tried:
$ git clone https://github.com/angular/angular-seed my_project && cd my_project
$ rm -rf app update_angular.js test/e2e/scenarios.js
$ touch test/e2e/scenarios.js
I then pasted code from AngularJS's official ngMock.$httpBackend docs into:
test/e2e/scenarios.js
'use strict'; // Line 1
function MyController($scope, $http) {...} // Lines 3-22
describe('MyController', function() {...} // Lines 24-87
Error
Unfortunately when I run the tests using config/karma-e2e.conf, I get:
ReferenceError: inject is not defined at
http://localhost:9876/base/test/e2e/scenarios.js?1387679134000:31
inject is defined in angular-mocks file, and is intended for unit tests only. If you're using Karma just add it to the files array.
e2e tests are on top of the browser, and run by angular-scenario. you can't inject any Angular components there.
BTW the Angular team are in the process of migrating their functional testing to protractor which is based on Selenium. I'd catch up with that instead of the angular-scenario testing framework. Protractor is a lot better.

Resources