I am trying to lay my hands on karma-jasmine and I am working on some basic examples to start with.
I have created one small plnkr which does 2 things only:
- Add the numbers
- display some hardcoded values on a button click
Here is my MainController.spec.js
:
describe('Main Controller', function () {
var $controller, MainController, UserFactory;
var data = {
"name": "Shashank",
"rank": "1"
}
beforeEach(angular.mock.module('app'));
beforeEach(inject(function (_$controller_, _UserFactory_) {
$controller = _$controller_;
UserFactory = _UserFactory_;
MainController = $controller('MainController', {UserFactory: UserFactory});
spyOn(MainController, 'add').and.callThrough();
spyOn(MainController, 'getHardData').and.callThrough();
}))
it('should be defined', function () {
expect(MainController).toBeDefined();
})
it('should have number = 3', function () {
expect(MainController.number).toEqual(5)
})
it('add() should assign value properly', function () {
// expect(MainController.add).toHaveBeenCalled();
})
it('getHardData should assign the exact data', function () {
// expect(MainController.getHardData).toHaveBeenCalled();
// expect(MainController.data).toEqual(data);
})
})
For the mentioned controller in the attached plnkr, I think I should only test 2 things:
- Test that the addition is working correctly.
- Test that the data after button is correct
Questions:
- Uncommenting any of the above lines thorw error:
Chrome 55.0.2883 (Windows 7 0.0.0) Main Controller add() should assign value properly FAILED
Expected spy add to have been called. at Object. (controller/MainController.spec.js:28:36) Chrome 55.0.2883 (Windows 7 0.0.0): Executed 4 of 4 (1 FAILED) (0.016 secs / 0.012 secs)
- Also, in
$controller('MainController', {UserFactory: UserFactory});
, I understand that we are assigning the values of factory but changing it to$controller('MainController', {});
is not throwing any error. WHY?
Please help me understand my silly mistakes.
Any good links to understand best practices/examples of karma & jasmine would be of great help