An open API service indexing awesome lists of open source software.

https://github.com/normandy72/testing-controllers

Testing AngularJS Controllers. Coursera course "Single Page Web Applications with AngularJS" by Yaakov Chaikin.
https://github.com/normandy72/testing-controllers

angular angularjs html html5 jasmine jasmine-tests javascript js test testing

Last synced: about 1 month ago
JSON representation

Testing AngularJS Controllers. Coursera course "Single Page Web Applications with AngularJS" by Yaakov Chaikin.

Awesome Lists containing this project

README

        

# Testing AngularJS Controllers
## - 1 -
### beforeEach Setup
```
describe("tests", function(){

beforeEach(module('myApp'));
});
```
`module('myApp')` - alias for angular.mock.module
```
describe("tests", function(){

beforeEach(function(){
module('myApp');
setupMock();
});

// let's see what goes here in the next part of the code
...
});
```
```
...
var $controller;
var mockService;
var myCtrl;

beforeEach(inject(function(_$controller_){
$controller = _$controller_;

// setting up a mock (fake) service
mockService = {};
mockService.aMethod = function(){
return 'fake-value';
};

myCtrl = $controller('MyCtrl', {MyService: mockService});
}));
...
```
`inject(...)` - alias for angular.mock.inject

`_$controller_` - angular mock injector strips off the '_'

### Test Method
```
...
it("should update init value on item add", function(){
myCtrl.addItem();
experct(myCtrl.value).toBe("fake-value");
});
}); // end of describe
```

### Include JS Files in SpecRunner.html
```

```
## - 2 -
### beforeEach Setup
```
beforeEach(function(){
module(function($provide){
$provide.service('MockService', function(){
var service = this;
service.aMethod = function(){
return 'fake-value';
};
});
});

module('MyApp');
});
...
```
```
...
var $controller;
var myCtrl;

beforeEach(inject(function(_$controller_, MockService){
$controller = _$controller_;

myCtrl = $controller('MyCtrl', {MyService: MockService});
}));
```
### Test Method
```
...
it("should update init value on item add", function(){
myCtrl.addItem();
experct(myCtrl.value).toBe("fake-value");
});
}); // end of describe
```
***
#### _Summary_
* Angular provides ngMock module to help with unit testing.
* To test a controller you need:
* Load module controller is in with `angular.mock.module('name');`.
* Use `$controller` to instantiate the controller you want to test.
* Use controller instance to invoke methods, access props, etc.
* Do most of the setup in beforeEach. At least `module('name')` loading, but maybe more.
* `$provide` service can be injected only into `module('name')`.
* For other services, use angular.mock.inject method.
***