Skip to content

Instantly share code, notes, and snippets.

@failpunk
Last active July 27, 2016 19:49
Show Gist options
  • Save failpunk/0c7cacc03800c896a8c26f7e8537a0e9 to your computer and use it in GitHub Desktop.
Save failpunk/0c7cacc03800c896a8c26f7e8537a0e9 to your computer and use it in GitHub Desktop.
Testing angular components without using module mock
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;
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