w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Unit testing Angular js Directive with Dependencies
I figured it out using the below stackoverflow thread Testing angularjs directive with dependencies Below is the code: describe('Directive: AppVersion', function () { beforeEach(module('MyApp')); var element; it('should have element text set to config value', inject(function ($rootScope, $compile, x,y) { var scope = $rootScope; element = $compile('<div class="someClass" xDirective >some Content</div>')(scope); expect($(element).find('.someClass').css('height')).toBe(config.version); })); }); inside the it block i'm injecting 'x' and 'y' modules which are dependencies to the directive Thanks

Categories : Unit Testing

Unit testing an AngularJS directive that watches an an attribute with isolate scope
For a $watch to get triggered, a digest cycle must occur on the scope it is defined or on its parent. Since your directive creates an isolate scope, it doesn't inherit from the parent scope and thus its watchers won't get processed until you call $apply on the proper scope. You can access the directive scope by calling scope() on the element returned by the $compile service: scope.input = someData; var e = $compile('<file data="input" filename="filename.csv"></file>')(scope); e.scope().$apply(); This jsFiddler exemplifies that.

Categories : Angularjs

Angular unit testing directive that uses transclusion not working as expected
The reason why the directive that uses transclude does not trigger the alert is because it has an isolated scope : scope: {} and you defined your callback in it : post: function(scope, element, attributes) { scope.func = function($event) { alert('the unit test should trigger this'); } } Due the transclusion, the directive and the transclude do not share the same scope but inherit from the same parent (see the doc even it is difficult to understand). If you want that the transclude element access to an element that is added to the scope by the directive, the directive must not create a new scope and add this function in the parent scope : scope: false, ... post: function(scope, element, attributes) { scope.func = function($event) { alert('the unit test should trigger t

Categories : Angularjs

testing Angular directive scope with jQuery loaded
I found the problem. I'm running my tests in PhantomJS and was pulling in jQuery 2.0.3. Downgrading to jQuery 1.10.2 made everything work again. I'm kind of surprised that PhantomJS would have a compatibility issue but that seems to have been the problem.

Categories : Angularjs

Angular JS/Karma Unit Testing with Angular UI-Router
At first glance I would say it looks like the $stateProvider is telling you you need to put an empty state in there. Add this to the list of states. state( '', { ... } )

Categories : Unit Testing

Unit Testing AngularJS Directive that uses ng-switch
Try this: Directive app.directive('getData', function () { return { restrict: 'E,C', // Added E so <get-data></get-data> works replace: true, transclude: true, scope: { myData: '@' // Removed @myData since it's not needed here }, template: '<div ng-switch on="myData">' + ' <div ng-switch-when="4">Real Data</div>' + ' <div ng-switch-when="5">False Data</div>' + ' <div ng-switch-default class="grid">No Data</div>' + '</div>' } }); Tests describe('get-data test', function() { var $scope, $compile; beforeEach(function() { module('plunker'); inject(function($rootScop

Categories : Angularjs

Unit Testing - Defining the scope of the test
I think you should test validator and service separately. Say for service test you can mock validator to return specific results without polluting your test logic with too many details (pseudo-code) test Should_Add_Category_Only_If_It_Is_Valid() { //given Category category = GivenACategory(); GivenValidatorAcceptsCategory(category); //when Bool result = service.AddCategory(category); //then AssertTrue(result); VerifyServiceHasCategory(category); } test Should_Reject_Invalid_Category() { //given Category category = GivenACategory(); GivenValidatorRejectsCategory(category); //when Bool result = service.AddCategory(category); //then AssertFalse(result); VerifyServiceDoesNotHaveCategory(category); }

Categories : Unit Testing

Unit testing a directive that defines a controller in AngularJS
Create the element in karma, then use the .controller() function with the name of your directive to grab the controller. For your example, replace the last couple of lines with these: elem = angular.element('<div example-directive></div>'); $compile(elem)($rootScope); var controller = elem.controller('exampleDirective'); Note, that given how you defined your directive, it should be by attribute, and not as an element. I'm also not 100% sure, but I don't think you need the scope.$digest; usually I just put anything that needs to be applied into a scope.$apply(function() {}) block.

Categories : Unit Testing

Unit Testing directive that adds class to element
You are not changing the route after you compiled the element - in between element = $compile(element)($rootScope); and expect(element.hasClass('active')).toBe(true);, insert a line like $browser.url(envs[count++]) and what you get.

Categories : Unit Testing

How to Unit Test Isolated Scope Directive in AngularJS
I'm not sure it's possible with isolate scope (although I hope someone proves me wrong). The isolate scope that gets created in the directive is, well, isolated, so the $watch method in the directive is different from the scope that you're spying on in the unit test. If you change scope: {} to scope: true, the directive scope will inherit prototypically and your tests should pass. I guess this isn't the most ideal solution, because sometimes (a lot of the time), isolate scope is a good thing.

Categories : Javascript

How do you mock directives to enable unit testing of higher level directive?
Being forced to think about this more myself, I have come up with a solution that fills our needs. All of our directives are attributes, so I created an attributeRemover directive for use during the unit tests. It looks something like this: angular.module("myModule").directive("attributeRemover", function() { return { priority: -1, //make sure this runs last compile: function(element, attrs) { var attributesToRemove = attrs.attributeRemover.split(","); angular.forEach(attributesToRemove, function(currAttributeToRemove) { element.find("div[" + currAttributeToRemove + "]").removeAttr(currAttributeToRemove); }); } } }); Then the html for the directive I'm testing looks something like this: <div my-highe

Categories : Unit Testing

Unit testing angular ng-resource
You are not using $httpBackend correctly. First, the definition of the mock response: $httpBackend.whenGET('/api/clients').respond(mockResponse); Then, later, the expectation: $httpBackend.expectGET('/api/clients'); $httpBackend.flush();

Categories : Angularjs

Unit test angular right-click directive
I choose an alternative approach. You can use a directive to bind specific action on right click, using the contextmenu event: app.directive('ngRightClick', function($parse) { return function(scope, element, attrs) { var fn = $parse(attrs.ngRightClick); element.bind('contextmenu', function(event) { scope.$apply(function() { event.preventDefault(); fn(scope, {$event:event}); }); }); }; }); Code example on JSFiddle

Categories : Unit Testing

Angular.js scope not updating in directive
You can set up the HTML for the directive like: <div mydirective="contractData.People.loading"></div> And within the directive itself, create an isolate scope binding to the loading property scope: { isLoading: '=mydirective' }, // rest of directive This creates a property on the directive's local scope that is bound to the attribute expression. Then you can refer to that scope property in the directive's template like: template: '<span ng-show="isLoading">loading</span>' Here is a fiddle

Categories : Angularjs

Best practices for unit testing angular directives
The question is that directive is meant to bind together user, DOM and Scope. All scope handling shall be done inside a controller (probably bound to your directive through controller: property). So, you should have a unit testing separated for you controller, without even touching the directive part. Then you shall test your directive. As it's mainly about DOM handling, you might want to test your real template, not a mocked one. In order to get the elements, as you need, you can use find() method. If you don't use jQuery at all, you can load it (before your AngularJs dependency) on unit testing and use element.find('#one'), for example. All AngularJs elements are extended jQuery elements, if you don't have jQuery on your project, then Angular uses jQLite, and you'll not have the select

Categories : Unit Testing

Unit Testing Angular js with bootstrap-ui dialog
I changed the test code to this: describe('deletion confirmation modal', function() { var $scope, ctrl, $dialog, fakeDialog, provider, resolveCallback; //this fake object replaces the actual dialog object, as the functions are not visible to the test runner. fakeDialog = { isOpen: false, open: function() { fakeDialog.isOpen = true; return { then: resolveCallback }; }, close: function() { return true; } }; resolveCallback = function(callback) { } beforeEach(function() { module(function($dialogProvider) { provider = $dialogProvider; }); inject(function(_$httpBackend_, $rootScope, $routeParams, $controller,

Categories : Javascript

Unit-test a angular controller function in a directive
In your case you could test the elements controller by accessing controllers functions from the compiled elements scope. The easiest way to access the scope of the element is by calling the #scope() function on the compiled angular element. it ('should have a function X on scope', inject(function($rootScope, $compile) { var element = $compile('<div test-directive></div>')($rootScope); expect(element.scope().myFunction).toEqual(jasmine.any(Function)); }); Heres a simple example of the following technique used in a jsFiddle.

Categories : Angularjs

Testing angular with karma: how to set scope
Short story: change the compiled element to <div hy-plugin-window content="content"></div> and I think it should work. The directive has an ISOLATE scope, which means it does not prototypically inherit from the "regular" scope. In your test, you are defining content on the regular scope, but the directive itself is encapsulated - it has isolated scope and therefore does not see the content property defined on the regular scope. You need to communicate that through the explicit interface of the component, which is content attribute.

Categories : Angularjs

Angular - Passing variables to the directive scope
<validate-price-dir validate-price="{priceValid: {'disabled': 'disabled'}}">Checkout</validate-price-dir> app.directive('validatePriceDir', function() { return { restrict: 'E', scope: { validatePrice: '=validatePrice' }, link: function(scope, el, attrs){ console.log(scope.validatePrice); } }; });

Categories : Javascript

Angularjs controller's $scope undefined whille unit testing and using Google Closure Library
I can see a scope problem with the code in your test. I commented directly in the code. describe 'menu controller', () => result= org1 : '' org2 : '' org3 : '' beforeEach () -> goog.require 'MyModule.controllers.Menu' inject ($rootScope, $controller, $http, $httpBackend) -> # here you define a variable inside a function... scope = $rootScope.$new() httpBackend = $httpBackend httpBackend.whenGET({SomeRequestOptions}).respond result menuController = $controller new MyModule.controllers.Menu(), {$scope : scope, $http : $http} it 'should get organisations properly', () -> # here you try to access the variable from outside the function expect(scope.org

Categories : Angularjs

Angular UI-Router testing scope inheritance
Scope inheritance is a feature of Angular. I therefore think that it is not necessary to test in my tests. My workaround is to test that the AccountCtrl works and then just put the values in the other tests: it("should set scope when account Ctrl loaded", inject(['$controller', 'security', function($controller, security){ // Add your behavior testing code here var $scope = $rootScope.$new(); var user = { first: 'First', last: 'Last', email: 'testuser@test.com', gender:'male', birthday:'password'}; security.currentUser = user; $controller('AccountCtrl', { $scope: $scope}); $rootScope.$digest(); // verify the initial setup expect($scope.user).toEqual(user); expect($scope.account).toEqual(user); }])); Then in the other tests I manually populate the values: it('should

Categories : Angularjs

Angular access controller scope from nested directive
Use <div ng-transclude></div> instead of <ng-transclude></ng-transclude> in the template of modal directive.

Categories : Angularjs

Transforming angular directive template when using isolated scope
The problem is that {{label}} does not exist on the isolated scope. You can solve this by passing a reference to the parent scope to the isolated scope inside your directive: return {     restrict: 'E',     replace: true,     scope: {     id:'@',       label:'@'     }, // in the directive! controller : function($scope){ $scope.label = $scope.$parent.label; } However this is not an advisable paradigm. As it means that the only data your directive can listen for is 'named'. So its better to use an attribute, (which is looks like you are doing). So... // in the directive! controller : function($scope, $attrs){ $scope.$parent.$watch($attrs.itemSource, function(itemSource){ $scope.itemSource = itemSource;

Categories : Angularjs

Angular.js Unit/Integration Testing - Trigger Link Function
It turns out that I have to initialize the module containing the factories stringEntryGenerateTemplate and stringEntryGenerateLinkFn, which is the same module that contains the userWrapperUsername directive by adding this into my test case: beforeEach(module('userWrapper', function() {})); where userWrapper is the name of the module. So the test case becomes: describe('UserWrapper Table string entry', function() { var $scope , $compile; beforeEach(module('userWrapper', function() {})); beforeEach(inject(function($rootScope, _$compile_) { $scope = $rootScope.$new(); $compile = _$compile_; })); it('should be in stateDisplay if the value is non empty', function() { var userWrapper = { orgData: { student

Categories : Javascript

Angular Unit Testing on Controller using a Service - Breaking on Inject
I think this is a problem of the dependencies of the module influences.controllers not being loaded. I tried a rather scaled down version of your program and got the exact same error as you. It was only after consulting this question here that I managed to get it. Do read the answer by the author, I think it'll be very helpful. Anyways, this is what you should probably do to load the actual ui.bootstrap and influences.services modules in the Test file: 'use strict'; /* jasmine specs for controllers go here */ describe('influences controllers', function() { // Change is here. Notice how the dependencies of the influences.controllers // module are specified separately in another beforeEach directive beforeEach(module('influences.controllers')); beforeEach(function() { module(

Categories : Angularjs

Unit Testing Angular Service that uses $timeout with Jasmine's Mock Clock
Do not make your test Async by using Jasmine's clock. Instead, use $timeout.flush() to synchronously maintain the flow of the test. It may be a bit tricky to setup, but once you get it then your tests will be faster and more controlled. Here's an example of a test that does it using this approach: https://github.com/angular/angular.js/blob/master/test/ngAnimate/animateSpec.js#L618

Categories : Javascript

Why ng-transclude's scope is not a child of its directive's scope - if the directive has an isolated scope?
Why ng-transclude's scope is not a child of its directive's scope if the directive has an isolated scope? ng-transclude designed to allow directives to work with arbitrary content, and isolated scopes are designed to allow directives to encapsulate their data. If ng-transclude didn't preserve scopes like that, any arbitrary content that you're transcluding would need to know the implementation details of your directive (i.e. it would need to know what's available on the isolated scope you created). If it's not a bug, how can a container directive pass data to it's content, if not by setting attributes like I tried. If the container directive and contained directives are coupled - i.e. you wrote both of them and need them to act together - then they should communicate via a shar

Categories : Angularjs

Angular directive with isolated scope "breaks" other directives (ng-required, ng-disabled)
The issue is that a scope applies to an entire DOM element (i.e., <input> in this case), and my-directive is creating an isolate scope that is then applied to ng-disabled and ng-required. The isolate scope doesn't prototypically inherit from the enclosing scope, so isActive isn't visible within it. You can map that scope property into the isolate scope by explicitly providing it as an attribute on the isolate scope, and then referencing the local version of the attribute from ng-required and ng-disabled. E.g., in the directive definition: scope: { myActive: '=' } The '=' sets up a 2-way binding to the expression given in the my-active attribute on that element, with local name myActive. In the <input> tag: my-directive my-active="isActive" ng-required="myActive" ng-disa

Categories : Angularjs

Manually trigger Angular data binding for an input field (for unit testing purposes only)
This is not right approach to do this in angular. You should do like this. Working DEMO Create function inside the $scope and change your variable value so that angular itself will update your input field as well as at all places where you have used(bind) this variable. Angular Function $scope.changeInput = function() { $scope.value="barfoo"; }

Categories : Angularjs

AngularJS: How to make parent directive using transclusion be compiled before the child directive?
did you try to transclude in the mother element ? in fooDir Directive: transclude: true replace: true template: "<div ng-transclude></div>" and after in the child barDir Directive require: '^fooDir'

Categories : Javascript

angularjs: directive creates two child scope(not isolation scope)? and how to get scope of an element?[Solved by clear answer]
it's hard to figure out without any jsfiddle for the context. What is your link function? and what is your controller function? By the way, it is the normal behaviour as documentation says transclude:true creates also a new scope. Look at here : https://github.com/angular/angular.js/wiki/Understanding-Scopes The transcluded and the isolated scope (if any) are siblings -- the $parent property of each scope references the same parent scope. When a transcluded and an isolate scope both exist, isolate scope property $$nextSibling will reference the transcluded scope. So if you want to access the 2 siblings from one another, you have to use a 2-way binding with their parent

Categories : Angularjs

Django unit testing; POST checkboxes with multiple values
So after trying out a couple other things, I'm basically going to say there is "technically" no answer to my question...I could not find any way to create a checkbox-type POST argument using HttpRequest. However, doing it the 'right' way with the Django test client as Hieu Nguyen suggested does allow for that capability. You just have to encapsulate the multiple options in parantheses, as: response = c.post('/success/',{ 'fname': 'A', 'lname': 'Student', 'email': 'me@name.com', 'passwd': 'password', 'conpasswd': 'password', 'class_choices': ('1','2'), })

Categories : Django

How do I connect between parent $scope, directive $scope and a modal $scope?
Like I said in the comment you can access the variables from the parent scope in the modal popups scope. HTML <div ng-app="app" id="app"> <div ng-controller="MainCtrl"> <label-select color="{{color}}"></label-select> <div class="flyout"> <ul> <li ng-click="setColor(color)" ng-repeat="color in colors">{{color}}</li> </ul> </div> </div> </div> JS var app = angular.module('app', []); app.controller('MainCtrl', function ($scope) { $scope.color = "#AAADDD"; $scope.colors = ["#AAA", "#BBB", "#CCC", "#DDD", "#EEE"]; $scope.setColor = function (color) { angular.element(".flyout").removeClass("show"); $scope.color = color;

Categories : Javascript

How to update $scope.items array order in response to user re-sorting the DOM array using Angular-UI ui-sortable directive
You are Missing ng:model <ul ui:sortable ng:model="list"> <li ng:repeat="item in list" class="item">{{item}}</li> </ul> Please check below working example Demo It display the updated array <div ng:repeat="item in list">{{item}}</div> Array is updated automatically by the directive

Categories : Angularjs

Angular.JS: click-to-edit directive form updates model, but http.post still uses "old" values
You have a timing problem. You need to be aware that chrome updates the message in console.log when the object you are printing changes. When your directive calls the callback, it didn't updated the value you are binding yet. You can see this by adding breakpoints with chrome (put them on the console.log calls). A quick solution to this problem is to call the callback inside a $timeout, since it will cause another digest to be executed and then you know the value already was updated: controller: function($scope, $timeout) { //... $scope.save = function() { $scope.value = $scope.view.editableValue; $scope.disableEditor(); $timeout(function() { $scope.saveCallback(); }); }; }

Categories : Angularjs

Is it possible to call functions from parent directive controller, when subsidiary directive has isolated scope
directives can share controllers via the require property, that you correctly specified. this is what Angular's docs on directives say about accessing the directive's controller (emphasis added): "require - Require another directive and inject its controller as the fourth argument to the linking function. The require takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the injected argument will be an array in corresponding order. If no such directive can be found, or if the directive does not have a controller, then an error is raised" IMHO, when applied to your case, this means that the link function where the controller is injected is the one in your child directive, not in the parent

Categories : Javascript

Is there any testing tool/framework for unit testing of Oracle ADF bounded task flow?
What sort of testing are you looking to undertake? Functional, stress/load? Looks to Selenium or Oracle Application Test Suite (OATS) for functional. Look to OATS or Apache JMeter as options for stress/load. The advantage of OATS over other options is it has intelligence built in to understand the ADF framework.

Categories : Unit Testing

How to prevent transcluding directive to create new child scope for the form directive?
An interesting question, but a problem that's easily avoided by using <form name="appForm" ng-submit="submit(appForm.$valid)"> and checking the parameter in the submit function. http://jsfiddle.net/udMJ7/ Another (perhaps better) option is to use this which is set to the scope of the last controller (in this case the form controller, which we want) $scope.submit = function(){ if(this.appForm.$valid){ //post the form!! } }; http://jsfiddle.net/udMJ7/1/

Categories : Angularjs

Unit-testing and Integration Testing for Large or Medium-Complexity System Models in SIMULINK
I would look into Simulink Design Verifier and Simulink Verification&Validation. Specifically, they offer features such as automated test generation and coverage analysis, which I think are applicable to your problem. As a side note... With regards to the matlab unit-testing framework which you mentioned in your post, this is basically a MATLAB implementation of the xUnit framework. So it obviously comes in handy if you want to be able to apply xUnit design patterns to tests of MATLAB code. The framework can be used to write tests for a Simulink model, but keep in mind that you have to be able to write the tests in MATLAB code. So this just means making use of the Simulink command-line interface (e.g. commands like set_param and sim) to setup and exercise your model, then use th

Categories : Unit Testing

When and why should I switch from functional Selenium testing to unit testing in a Django web app?
I'm using both selenium and unit tests right now, and here are some of my thoughts: Unit test run faster than selenium scenario tests. Unit tests are easier to write then selenium scenario tests. Unit tests are much more granular than selenium scenario tests. Unit tests are less brittle than selenium scenario tests. My selenium tests tend to run in a matter of minutes (they are several pages long) as compared to unit tests which are designed to run in less than a second. I have to spend a lot of time setting up the environment for a specific selenium test and then run it, and then check that the entire environment is in the right state. To test even a slightly different scenario, say, what happens if someone enters a bad value for one field, I have to start over from scratch. Unit tes

Categories : Django



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.