After placing the issue on github I received the answer I was looking for.
This can be found HERE!
Protractor requires that Angular be present on the page and the way around
this is to use the driver directly. Following the link above should stear
anyone stuck on the same issue in the right direction.
Kudos to JulieMR and the others who helped out with this issue.
In the AngularJS 1.2 and Beyond meetup last night they talked about
Protractor and said that they are migrating all of their end to end tests
to Protractor. It sounded like this is in the early stages but is the
direction they are going. The slides are at:
https://docs.google.com/presentation/d/1WHCcp3G3HxoE7b_ut_ERKJF4zQK_P4qFlESjE2E9AUQ/edit
and I assume the video will be available in a couple of days. Here's the
link to the meetup:
http://www.meetup.com/AngularJS-MTV/events/120927882/
btw, there was a ton of really interesting info in the meetup -- well worth
the watch.
Normally in a directive the this is window, but because you are using
strict mode it is changed to undefined. This is to stop people accidentally
modifying the global object when using the constructor pattern without
using the new keyword.
If you remove the "use strict"; you will see no errors, but if you
console.log(this) you will see window, which you shouldn't be adding
methods to like that anyway. I suggest you just do
var link = function() { ... };
In the CHROME browser version the error occurs when angular tries to load
JQLite a api-compatible subset of the jQuery library that allows angular to
manipulate the DOM. I was able to fix the issue by downloading
uncompressed versions of jQuery (v1.10.2), angular (v1.0.7), and
angular-mocks (v1.0.7). I added the following to the configuration in the
jasmine-maven-plugin.
<preloadSources>
<preloadSource>${angular-test-deps}/jQuery.js</preloadSource>
<preloadSource>${angular-test-deps}/angular.js</preloadSource>
<preloadSource>${angular-test-deps}/angular-mocks.js</preloadSource>
</preloadSources>
The angular documentation states that "Real jQuery always takes precedence
over jqLite, provided it was loaded before DOMContentLoaded eve
The test method is defined on RegExp objects. Try this:
var reg =
/^(?:https?://)?(?:www.)?(?:youtube.com|youtu.be)(?:/)(?:watch?v=)?([^&]+)/;
Or this:
var reg =
RegExp("^(?:https?://)?(?:www.)?(?:youtube.com|youtu.be)(?:/)(?:watch?v=)?([^&]+)");
The first parameter to the iterator in forEach is the value and second is
the key of the object.
angular.forEach(objectToIterate, function(value, key) {
/* do something for all key: value pairs */
});
In your example, the outer forEach is actually:
angular.forEach($scope.filters, function(filterObj , filterKey)
As mentioned in the comments I am using angular 1.1.5 (for the new
ng-animate). To get my tests passing I needed to install the angular-mocks
1.1.5.
bower install angular-mocks-unstable
or update the bower.js (or components.js) file and run:
bower install
And update my karma.conf.js file
files = [
JASMINE,
JASMINE_ADAPTER,
'app/components/angular-unstable/angular.js',
'app/components/angular-mocks-unstable/angular-mocks.js', // need
unstable here
'.tmp/scripts/*.js',
'.tmp/scripts/**/*.js',
'.tmp/spec/**/*.js'
];
The only valid scenario I can think of for you to do that is to perform
end-to-end tests. In such a case, you should use the passThrough method of
the request handler returned by the when method of the
ngMockE2E.$httpBackend service.
More information on that matter here.
401 is an http error, not a redirect. Most servers send a 302 (moved
permanently) but sometimes the developers change things to send a 301
(moved temporarily). Additionally, you should also be testing the value of
location.path() and not window.location.
controller = $controller("app.controllers.merchant.create",
$scope: scope,
$location: location
"app.services.user": user
"app.services.sector": sector
keyboardManager: bind: ->
)
The mistake was that I tested the create controller, but I wrote edit there
:P
Yeah, the E2E input() method is sort of a nuisance as it does a find based
on the ng-model of a particular input.. So for situations like ng-repeat,
it doesn't lend itself to any practical use.
Good news is, you can get the functionality you want just using element().
element('my_element_here').val('Value I want to enter!')
expect(element('my_element_here').val()).toEqual("Value I want to enter!")
Basically, the element() call can be chained with any of these jQuery-esque
methods:
val, text, html, height, innerHeight, outerHeight, width, innerWidth,
outerWidth,
position, scrollLeft, scrollTop, offset.
The E2E Test harness for Angular is... interesting. And in desperate need
of some TLC. But it's actually pretty good at what it does, once you get
over the awkwardness of it! (And assu
Regarding the first problem: You can load the modules you need like this:
var $httpBackend; // reference for your it() functions
beforeEach(function () {
module('myApplication');
inject(function ($injector) {
$httpBackend = $injector.get('$httpBackend');
});
});
Now, about the unexpected request problem, from the angularjs httpBackend
documentation:
The $httpBackend used in production, always responds to requests with
responses asynchronously. If we preserved this behavior in unit testing,
we'd have to create async unit tests, which are hard to write, follow and
maintain. At the same time the testing mock, can't respond synchronously
because that would change the execution of the code under test. For this
reason the mock $httpBackend has a flush() method, which
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
In your case, you have to $digest twice, once for $httpBackend, and again
for your own deferred.
So:
it('should return a allowed content type collection given a document id',
function(){
var collection;
contentTypeResource.getAllowedTypes(1234).then(function(result){
collection = result;
});
$httpBackend.flush();
$rootScope.$digest();
expect(collection.length).toBe(3);
});
You can mock the Http GET request and test the service like this
describe("getCustomers", function (service) {
beforeEach(module('app'));
var service, httpBackend;
beforeEach(function () {
angular.mock.inject(function ($injector) {
httpBackend = $injector.get('$httpBackend');
service = $injector.get('service');
})
});
describe('getCustomers', function () {
it("should return a list of customers", inject(function () {
httpBackend.expectGET('/Home/Customers').respond(['david',
'James', 'Sam']);
service.getCustomers(function (result) {
expect(result).toEqual(["david", "James", "Sam"]);
});
httpBackend.flush();
}))
})
});
Working Demo
I'm not entirely sure this would apply to testing a directive as I have yet
to do so myself. However; When testing services and controllers, what I
will usually do is start nesting describe blocks.
I'm not too familiar with Jasmine, or any potential performance issues this
may cause (it's something I'm planning on checking out), but if anyone has
something to share on that please do.
So what I'm doing is something like this:
describe("myDate", function() {
var $compile, $rootScope;
var validDate, invalidDate, invalidDateFormat;
beforeEach(angular.mock.module('main'));
beforeEach(inject(
['$compile','$rootScope', function($c, $r) {
$compile = $c;
$rootScope = $r;
}]
describe("validDate", function () {
it("should check if the given date is a va
I have never worked with AngularJS before, but I think what is going on
here is that your parameter p is not your simple key/value object but a
more complex AngularJS object. By assigning your prod to it you are
overriding it instead of changing specific parts of the object.
Maybe the following code snippet will help you out:
for(var key in prod) {
p[key] = prod[key];
}
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.
You're using old karma's configuration style. I see two options
1) you have quite old karma version,
2) you are trying to run new karma on the old configuration style.
You should try to upgrade karma to the newest version and migrate your
configuration to the new style, see:
http://karma-runner.github.io/0.10/config/configuration-file.html
By the time you call the config function your module is in the run phase.
At that point you can no longer inject a provider. Try moving the function
that has someServiceProvider injected into it.
beforeEach(module('myModule', function(someProvider) {
someProvider.configure(1);
}));
it('should work now', inject(function(some) {
expect(some.func()).toBeAvailable();
}));
The problem is that you're not including the right JS files here.
Note that Angular UI bootstrap JS file didn't include the ui-tinymce
module. So as a first step , remove the Angular JS bootstrap module and
include the ui-tinymce JS file which is avaiable in Github.
Secondly, the angular-tinymce module has a dependency on the original core
tinymce.js file. So you've include that js file also.
I actually forked your plunkr and fixed these issues. Please see the code
and find the changes.
http://plnkr.co/edit/6OpbZM?p=preview
( There was a script file loading issue in Plunkr when I try to fetch
directly from Github, So I included that ui-tinymce.js as a local file )
You would write something along these lines:
describe('MyApp controllers', function() {
describe('MainCtrl', function(){
it('should populate the query', function() {
var scope = {},
ctrl = new MainCtrl(scope);
expect(scope.mainpage).toEqual(someMainPageMock);
});
});
});
This is well documented, see the AngularJS tutorial for a quick reference,
it's also suggested to read the Jasmine docs (!).
You'd also want to spy on the query() method, see here on how.
Avoid initialize application level module, put your controllers in
myApp.controllers and test this module instead.
"We recommend that you break your application to multiple modules. (...)
The reason for this breakup is that in your tests, it is often necessary to
ignore the initialization code, which tends to be difficult to test."
http://docs.angularjs.org/guide/module
Yes, you can run a subset of tests.
Use iit instead of it on the tests you would like to run and the others
will be skipped.
Example:
describe('TestCtrl', function() {
var $scope;
iit('should have scope', function() {
expect($scope).toBeDefined();
});
it('should have scope', function() {
expect($scope).toBeDefined();
});
it('should have scope', function() {
expect($scope).toBeDefined();
});
});
This will cause only the first test to be run and the others to be skipped.
As soon as Jasmine detects a test with iit, it will skip the all tests with
it.
This is very handy if you need to test only one or two tests you are
working on when you have defined a whole suite of tests.
This also works when you replace describe with ddescrib
So, this is because Api.authenticatePlayer is calling to a different path
than what you are expecting.
Your test should have this instead:
this.$httpBackend.expectPOST('http://domain.com/auth/player',
postData).respond(200);
Basically, in your test, $httpBackend is a mock of the code that would call
your API. You get to say "When my code calls this URL, respond with _".
In this code, you are saying that you expect the post to happen and to
return an empty response of 200. You could replace "200" with the json
payload that you want to pretend that the server responded with.
You can only access protected members from your own base class instance...
not one provided to you as a parameter. It's all about OO encapsulation
really. Without this restriction, the object under construction could
invalidate invariants of the baseTest& parameter.
Put another way, your SubTest may decide on a use for a protected member
that conflicts with the usage made of the same member by another
BaseTest-derived class (say SubTest2 : BaseTest). If your SubTest code was
allowed to fiddle with the other object's data, it could invalidate the
invariants in a SubTest2 object, or get some values out that were - in the
intended encapsulation - only meant to be exposed to SubTest2 and
(optionally - see below) SubTest2 derivatives.
Followup question:
Why is it, that in the adde
As far as I understand your problem, you want to log requests in case there
is a binding error. A binding error is somewhat exception so that you may
handle exceptions of your controller or actions. To do this, you need to
useExceptionFilterAttribute . The example below :
public class ExceptionHandlingAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext
actionExecutedContext)
{
string content =
actionExecutedContext.Request.Content.ReadAsStringAsync().Result;
///LOGGING ACTIONS
base.OnException(actionExecutedContext);
}
}
There's a blog entry dedicated to that question here.
In short, working with primitive values is faster most of the time because
of optimizations made by most JS engines. However, that might not be the
case when accessing non-native members on primitives.
For instance, we can read in the article that:
In the SpiderMonkey JS engine, for example, the pseudo-code that deals
with the “get property” operation looks something like the following:
// direct check for the "length" property
if (typeof(value) == "string" && property == "length") {
return StringLength(value);
}
// generalized code form for properties
object = ToObject(value);
return InternalGetProperty(object, property);
Thus, when you request a property on a string primitive, and the
pro
Heres a working example of what you are trying to do
fiddle: http://jsfiddle.net/yjTXK/1/
var Obj1 = function (){
this.getResult = function() {
var result = 5*5;
return result;
};
this.answer = this.getResult();
};
var Obj2 = function(obj1) {
//assign the answer to this.x, var doesn't 'live' outside of the
constructor
this.x = obj1.answer;
};
//you make an instance of obj1, this is different from the 'class' Obj1
var testobj1 = new Obj1();
//then you pass that instance into an Obj2, so it can be consumed
var testobj2 = new Obj2(testobj1);
console.log(testobj2.x);
W3Schools has quite a good primer on Javascript Objects which should get
you familiar with the basics.
Update, why pass in the instance of Obj1 into Obj2?
You need to provide the sec
Moment of clarity: the solution is to use a SerializerMethodField to
instantiate the RepSummarySerializer and pass the customer_id in the
context:
class CustomerSummarySerializer(serializers.HyperlinkedModelSerializer):
id = ...
name = ...
rep = serializers.SerializerMethodField('get_rep')
def get_rep(self, obj):
rep = obj.rep
serializer_context = {'request': self.context.get('request'),
'customer_id': obj.id}
serializer = RepSummarySerializer(rep, context=serializer_context)
return serializer.data
The customer_id can now be accessed in RepSummarySerializer.get_rep_url
like this:
def get_rep_url(self, obj):
customer_id = self.context.get('customer_id')
...
Don't know why I didn't think of this thr
Your properties in your Tile class are set to private. To be able to access
the properties from outside the class you will need to declare them as
public:
public class Tile
{
public int ID { get; set; }
public string Name { get; set; }
public double Frequency { get; set; }
public double Divider { get; set; }
public int Value { get; set; }
public int Turns { get; set; }
public int StartLevel { get; set; }
}
You can keep your same constructor, although that will end up being a mess
to maintain as you add/subtract properties. Another way you can instantiate
your list of Tile objects is like so:
List<Tile> tList = new List<Tile>
{
new Tile
{
ID = 0,
Name = "Example1"
}
};
...for as many public properties as you need to set
You can check this way:
if( attr["datepicker"] == "myOnSelectMethod" &&
typeof myOnSelectMethod === "function" ){
// ...
}
Or even:
if( typeof scope[attr["datepicker"]] === "function" ){ // Instead of
`scope`
// ... // may be any other
object,
} // `window` for
example
Angular does not process the value attribute. If you want to initialize the
model value to something in the input, you need to use ng-init, f.ex.
<input ng-model="foo" ng-init="foo = 3">
You can put the initialization code in the directive and pass in the the
data you need:
<input my-cell ng-class="'lib_name inline_div'" type='text' value="{{
lw.library.name }}" >
Then the directive changes to something like this:
angular.module('Demo').directive("myCell", function(){
return {
function(scope, element, attrs){}
scope.row = row;
scope.column = column;
scope.CellStore.addCell(scope.lane.lane, row, column,
attrs.value);
};
}) ;
Since I can't see the rest of your app code, you may need to change some of
the variable names to get it to work, but the basic premise is to just use
the link function of the directive to run your initialization. Also, in the
directive you have access to the inhe
When your page is built you would have session scope already. We did
something like this by simply passing session id to an app level JavaScript
variable in view layout, in our case we use HAML. Something like below in
head block before ng-app kicks in.
globalAppCtx = {}
globalAppCtx['user'] = JSON.parse("#{escape_javascript
session[:user].to_json}");
In above code, session[:user] is ruby session with user literal containing
relevant Hash that was required in ng-app. Else where, in the angular code
or elsewhere in JavaScript, you can refer to globalAppCtx['user']
IMO this shouldn't be very expensive and saves you an AJAX request to get
the value. I could not think of any downside of this approach.
Try passing the result variable with the broadcast.
$rootScope.$broadcast('toggleVForum',{result: this.result});
controllerComm is not defined in the $on listener even though you may be
injecting it into the controller where the listener is defined.
$scope.$on('toggleVForum',function(evt,args){
$scope.isVisible = args.result;
...
});
youll have to include permission decorators on your views , further info is
here https://docs.djangoproject.com/en/dev/topics/auth/ , &
https://docs.djangoproject.com/en/dev/topics/auth/default/#topic-authorization
so if you want to limit your updateview to any user with the ManytoMany
attribute 'administrator', youll have to do something like this:
views.py
from appname.users.decorators import requiresGroup
from django.contrib.auth.decorators import login_required
class UniversityUpdateView(UpdateView):
model = University
form_class = UniversityForm
template_name='university_form.html'
@method_decorator(requiresGroup("groupname" ,
login_url='/accounts/login/'))
def dispatch(self, request, *args, **kwargs):
return super(UniversityUpdateView, self).dispatc
Yes, that's the wrong type of shell. That refers to Shell extension type,
which is one of the LightSwitch extension types for customising it. A Shell
handles the layout of all of the controls of the application uses to
display itself.
You need to use the AutomationFactory (which is only available for
out-of-browser applications) to access the type of shell object that you're
wanting:
If (AutomationFactory.IsAvailable = True) Then
Dim shell = AutomationFactory.CreateObject(APPLICATION_ID)
shell.ShellExecute()
End If
I think that's by design. NUnit is designed to clean up the environment
before any test, to generate same conditions for any test independent their
execution order.
If Test A would change the XDocument, Test B would be run with that
changes. That might led to indeterminate test results.
If Test B expects changes made from Test A, then your tests are not fully
isolated, that's a bad practice.
If you wan't to change that behaviour, implement a lazy field and load the
test data only on first access. You can increase performance if you know
that you are not changing data in any of your tests, but pay attention.
private static Lazy<IEnumerable> testData = new
Lazy<IEnumerable>(GetExample);
private static IEnumerable GetExample() {
var doc = XDocument.Load("Example.xml");