I started learning how to test Angular apps, and ran into some problems.
I generated an Angular app using Yeoman. yo angular --minsafe AppName
Then generated a service yo angular:service MyService
Wrote a simple method in the service, and a test for it, just to make sure that everything was working. I ran grunt test
and the tests passed.
Now it gets interesting, as I added Underscore to the mix using bower install underscore
and added a <script>
tag for it in the index.html
.
Then I added some simple code to the service method, just _.map([1,2,3], function(el){return el+1});
to see if Underscore was working.
I ran the tests again grunt test
, and it failed saying that _ is not defined
.
I tought that, because Underscore attaches the _ variable to the window object, it would be available for the testing. Am I wrong?
Also, when I ran the application in the browser, Underscore was defined and working.
So, my question is, how do you test an Angular app that uses Underscore? Is this a common problem or am I doing something wrong?
Thanks, Petar
Testing in AngularJS is achieved by using the karma framework, a framework which has been developed by Google itself. The karma framework is installed using the node package manager. The key modules which are required to be installed for basic testing are karma, karma-chrome-launcher ,karma-jasmine, and karma-cli.
If a directive creates its own scope and you want to test against it, you can get access to that directive's scope by doing var directiveScope = myElement. children(). scope() - It will get the element's child (the directive itself), and get the scope for that.
AngularJS also provides the ngMock module, which provides mocking for your tests. This is used to inject and mock AngularJS services within unit tests.
If you see the karma.conf.js
file generated by Yeoman, you will see that bower components are not added automatically.
// list of files / patterns to load in the browser
files = [
JASMINE,
JASMINE_ADAPTER,
'app/bower_components/angular/angular.js',
'app/bower_components/angular-mocks/angular-mocks.js',
'app/scripts/*.js',
'app/scripts/**/*.js',
'test/mock/**/*.js',
'test/spec/**/*.js'
];
Just add the underscore folder to it and you won't have any issues.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With