Last active
July 27, 2016 19:49
-
-
Save failpunk/0c7cacc03800c896a8c26f7e8537a0e9 to your computer and use it in GitHub Desktop.
Testing angular components without using module mock
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let Component = { | |
template: ` | |
<div> | |
<h1>{{$ctrl.title}}</h1> | |
<form ng-if="!$ctrl.successs"> | |
form data... | |
</form> | |
<div | |
id="success-block" | |
ng-if="$ctrl.successs"> | |
{{$ctrl.success}} | |
</div> | |
</div> | |
` | |
} | |
class Controller { | |
constructor() {} | |
$onInit() { | |
this.title = 'My Component'; | |
this.success = ''; | |
} | |
onSuccess() { | |
this.successs = 'Success!!'; | |
} | |
} | |
Controller.$inject = []; | |
Component.controller = Controller; | |
export default Component; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import MyComponent from './my.component'; | |
describe('Component: forgot-password', function () { | |
let element, $rootScope, scope, $compile, component; | |
beforeEach(inject(($injector) => { | |
$rootScope = $injector.get('$rootScope'); | |
$compile = $injector.get('$compile'); | |
// init our controller | |
component = new MyComponent.controller(); | |
component.$onInit(); | |
// init scope and attach our controller | |
scope = $rootScope.$new(); | |
scope.$ctrl = component; | |
// compile the template | |
element = $compile(MyComponent.template)(scope); | |
scope.$apply(); | |
})); | |
it('should show the form and have the success block hidden', function () { | |
expect(find('#success-block').length).toEqual(0); | |
expect(find('form').length).toEqual(1); | |
}); | |
it('should show the success block and remove the form', function () { | |
component.onSuccess(); | |
scope.$apply(); | |
expect(find('#success-block').length).toEqual(1); | |
expect(find('form').length).toEqual(0); | |
}); | |
/** | |
* Helper to find elements in the template | |
*/ | |
function find(selector) { | |
return angular.element(element[0].querySelector(selector)); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment