Unable to populate Backbone collection with sinon + jasmine - backbone.js

I have the same problem that was asked here
the author of the question mentioned that he was able to solve it by using the standalone version of jasmine over the headless webkit.
In my tests i use only a standalone version of jasmine and still having the same problem.
Here is my code:
describe 'Shared Collections Specs', ->
describe 'Channel Collection', ->
describe 'When fetching channels', ->
responseFixture = null
channelCollection = null
server = null
beforeEach ->
channelCollection = new ChannelCollection()
responseFixture = [{id: 3, name: 'foo'}, {id: 1, name: 'bar'}, {id: 2, name: 'baz'}]
server = sinon.fakeServer.create()
server.respondWith('GET', 'enspoint/channels', [
200, {'Content-Type':'application/json'}, JSON.stringify responseFixture
])
afterEach ->
server.restore()
it 'should populate the collection', ->
channelCollection.fetch()
server.respond()
expect(channelCollection.length).toEqual responseFixture.length
The collection is always empty insted of expected length of 3 it fails with Expected 0 to equal 3.
I tried to use jasmine waits and runs as i thought there might be something async in the process but i'm getting the same result.
Any ideas?

Just an innocent observation, but there might be a typo in the URL "enspoint/channels" in your XHR fixture. For example, did you mean "endpoint/channels"?

Related

How to add component to a test case using API?

I created a test case using tcms_api
test_case = rpc_client.TestCase.create({
'summary': 'My testing',
'product': 2,
'category': 2,
'priority': 1,
'is_automated': True,
'text': 'my first test case',
'case_status': 2, # CONFIRMED
})
I wanted to add component to the test case, but could not find a sample or the syntax in API document. I tried the following with my guess and the update in change log:
rpc_client.TestCase.add_component(test_case['id'], [3, 6])
I got the error below. Can you please advise how to construct the query for component query? Thanks.
xmlrpc.client.Fault:
Fault -32603: 'Internal error: Component matching query does not exist.'
From the documentation the signature of this method is:
function:: XML-RPC TestCase.add_component(case_id, component_id)
The docs tell you that component_id is an int, not a list.
^^^^ scratch that, the documentation is slightly wrong.
The second parameter is a string which should be the component name!

How to programmatically fill values in successive select in AngularJS?

Programmatically
So I am facing an issue with the select in Angular JS. This is a follow-up question to my previous question
Now I am able to load my values in the second select but I am unable to write the same value to it when the query from DB comes back. So If I select Ford in one select and Figo in another. and press save. The values go into DB correctly but when I come again to that view. Shouldn't that value persist right? I mean I should be able to see figo in the second select. But I am unable to. I tried setting to the ng-model but that method doesn't work. I have also attached a fiddle with the proper comments as to what is not working.
The code uses one of the marked answers from the question.
HTML
<select ng-model="carBrand" name="carBrand" required ng-options=" brand for brand in brands" ng-change="selectedCar(carBrand)"></select>
<select ng-model="carModel" name="carModel" required ng-options="model.name for model in cars[carIndex]"></select>
JS
$scope.brands = ['Ford', 'Honda', 'Hyundai', 'Mahindra',
'Maruti Suzuki', 'Nissan', 'Renault', 'Skoda', 'Tata', 'Toyota', 'Volksvagen'
];
$scope.cars[0] = $scope.cars[0] = [{
name: "Figo",
capacity: 45
}, {
name: "Ecosport",
capacity: 52
}, {
name: "Fiesta",
capacity: 45
}, {
name: "Endeavour",
capacity: 71
}];
$scope.carBrand = $scope.brands[0];
$scope.cars = [];
$scope.selectedCar = function(brand) {
$scope.carIndex = $scope.brands.indexOf(brand);
};
$scope.carModel = "Anything";
EDIT
I think there is an issue in the understanding of the question. All I want is programmatically(by code) set the value of the second select. That's it.
I have forked your fiddle. Have a look: https://jsfiddle.net/4ynkrj0o/2/
var MockSaveMyData = function(itemsToSave){
// I JUST SAVED ALL MY DATE !! :D
var savedItems = itemsToSave;
savedItems.CreatedAt = new Date();
savedItems.CreatedBy = 'YOU !!';
return {
then: function(callback){
callback(savedItems);
}
};
};
You will have to save and retrieve the values on every page refresh.
Like you said, you have cookies where you save your Car object. In that case, you will have to assign the object on the top firth thing inside the controller.
You will also have to update the cookies after you have run the save function. I will suggest doing all this in the success call back which http calls provide. You can update the cookie and then refresh the page. Or you can just assign the updated values and give a message to the user stating that the save call has been successful.
Again, in my opinion, you should avoid reloading the page. It almost defies the essence of Angular. Where you can do almost everything asynchronously.

Angular $resource returns too many results

I don't know if my question makes any sense as I'm a bit confused to what is happening here myself, but I have a service that returns information about offices. There seems to be nothing wrong with this and it returns data like this:
[
{
"mainContact": {
"phoneNumbers":[
{"key":1,"number":"22555555","type":"Mobile"}
],
"key":1,
"name":"Ola Dunk",
"email":"oladunk#lol.no"
},
"secretary": {
"phoneNumbers": [
{
"key":2,
"number":"22666666",
"type":"Home"
}
],
"key":2,
"name":"Kari Norrmann",
"email":"kari#test.no"
},
"key":1,
"specialRequirements":null,
"name":"Ola Dunk",
"address":"Test",
"doctorCount":10,
"presumedPurchaseAmount":100000,
"phoneNumber":"22222222",
"membershipStatus":1
}
]
I tried using $resource to get the data using
var r = $resource('http://localhost:60297/api/office');
console.log(r.query());
I use query() over get() since this is the default get all service when no id is specified or some other selector. It just happens to return only the one test office I've created because that's the only office that exists presently.
My problem is what you can see in my console which I've screenshotted here:
That's just the tip of the iceberg. The result keeps getting repeated. Just to check I tried using $http instead of $resource and then it works just fine.
Any ideas on what's wrong?
That's because object 'self-assigned', you can try in console:
var test = { foo : 'bar'};
test.foo = test;
and get same thing. The question is: why it bothers you?

AngularFire ObjectFactory Childobjects cause Circular Dependency

Using AngularFire, I am extending the object factories in order to have encapsulated data and to allow specific features, as explained in the official tutorial. I have a data structure like the following:
{
'articles': {
'article-asd876a': {
title: 'abc',
text: 'lorem ipsum ...',
comments: {
'comment-ad4e6a': true,
'comment-dsd9a7': true
}
}
},
'comments': {
'comment-ad4e6a': {
text: 'comment text1',
articleId: 'article-asd876a'
},
'comment-dsd9a7': {
text: 'comment text2',
articleId: 'article-asd876a'
}
}
}
Now I would love to be able to do this:
var article = new Article(8); // Returns the object created by my object factory, fetching data from firebase
var comments = article.getComments(); // Returns an array of type Comment
var firstText = comments[0].getText();
var article2 = comments[0].getArticle(); // article2 === article
But this fails for me on many levels. One of them being: In Article, I can only store the Comment ID, and therefore have to recreate the Comment Object using new Comment(commentId), for which I need to inject Comment into Article. The same is true for Comment, so that I end up with a circular dependency Article -> Comment -> Article. The following fiddle shows the behavior: http://jsfiddle.net/michaschwab/v0qzdgtq/.
What am I doing wrong? Is this a bad concept/structure for angular? Thanks!!
What am I doing wrong? Is this a bad concept/structure for angular?
Thanks!!
You are creating circular dependencies.
I can do var Comment = $injector.get('Comment'); to avoid the error,
is that the best solution?
I see two solutions:-
1) Lazy injecting solution (you suggested yourself)
This is the best solution to avoid those circular dependencies in AngularJS. Although looking at the AngularFire documentation you are into an uncharted territory as some of these things in AngularFire are experimental in nature.
Here is the working fiddle from your
var Comment = $injector.get('Comment');
You are essentially lazy injecting your references.
http://jsfiddle.net/yogeshgadge/ymxkt6up/5/
2) Module Run block:
With this option you may be able to inject those dependencies into your factories instead of using $injector.

How to generate the right data structure for ngoptions in single request

I'm trying to return a data structure for an Angular screen with several dropdowns.
I don't want to make multiple requests to get the options for each select so I was hoping to create a single nested data structure in Django that contains all the options for each select (there are only a small number)
Angular wants something like this to use with the select and ngoptions directives:
{'booking_name': 'acme',
'current_sales_person': 2,
'sales_people_options': [
{id: 1, name: 'rod'},
{id: 2, name: 'jane'},
{id: 3, name: 'freddy'}
],
... lots more fields here ...
}
sales_people_options would populate the options for the dropdown and current_sales_person indicates which salesperson is initially selected.
How can I get Django Rest Framework to return this in a single request from a ModelSerializer?
I could just create the JSON directly via JSONRenderer but I've got a lot of other fields so I'm keen to use ModelSerializer.
The only way seems to be to add a method called sales_people_options to my Model.
However - I've got several of these fields to generate and it seems very wrong to add model methods for something that I only need for one specific serializer.
EDIT - I think I might need to subclass serializer.Field and override a method (probably field_to_native).
This is just a json object. The Django rest framework is capable of returning json strings which you can then JSON.stringify the string returned to turn it into an object angular is expecting.
{'booking_name': 'acme',
'current_sales_person': 2,
'sales_people_options': [
{id: 1, name: 'rod'},
{id: 2, name: 'jane'},
{id: 3, name: 'freddy'}
Checkout the Django JSON renderer; http://www.django-rest-framework.org/api-guide/renderers
This might be a weird way to do it but it worked:
class BookingSerializer(serializers.ModelSerializer):
class UserOptionsField(serializers.Field):
def field_to_native(self, obj, field_name):
return User.objects.all().values('id', 'username')
sales_people_options = UserOptionsField()
class Meta:
model = Booking
fields = (
'id', 'booking_no', 'current_salesperson', 'sales_people_options',
)
EDIT: And here's a generic solution:
class ModelOptionsField(serializers.Field):
def __init__(self, source=None, label=None, help_text=None, queryset=None, fields=None):
self.queryset = queryset
self.fields = fields
super(ModelOptionsField, self).__init__(source, label, help_text)
def field_to_native(self, obj, field_name):
return self.queryset.values(*self.fields)
that you use like this:
class MySerializer(serializers.ModelSerializer):
my_options_list = ModelOptionsField(queryset=User.objects.all(), fields=('id', 'username'))

Resources