I am testing a cancelWebSiteBuyRequest function that makes a call to a put request. I have done this many times but for some reason here I keep getting the error:
Expected spy put to have been called with
[ '/:orgId/WebSites/:webSiteId/BuyRequests/:requestId/Cancel', { orgId : 19, webSiteId : 4, requestId : 5432 }, { message : 'this is my
campaign post' } ]
but actual calls were
[ '/:orgId/WebSites/:webSiteId/BuyRequests/:requestId/Cancel', { orgId : 19, webSiteId : 4, requestId : 5432 }, { message : { message :
'this is my campaign post' } } ].
I have done this the same way many times but I cannot find what I missed that causes the passed message to be called as the full object and not just the string I am pointing it too.
Function I am testing:
this.cancelWebSiteBuyRequest = function (orgId, webSiteId, requestId, message) {
var deferred = $q.defer();
apiResource.put('/:orgId/WebSites/:webSiteId/BuyRequests/:requestId/Cancel', { orgId: orgId, webSiteId: webSiteId, requestId: requestId }, { message: message })
.then(function (data, status, headers) {
deferred.resolve(data);
}, function (data, status, headers) {
deferred.reject("There was a problem canceling this buy request.");
});
return deferred.promise;
};
Test:
describe('webSiteBuyRequestService', function () {
beforeEach(module('pb.webSites.services'));
var mockApiResourceProvider;
var continuationToken = {
nextPartitionKey: 4352632,
nextRowKey: 613
};
var mockAccount = {
//entityId: 'r43',
//accountId: 436675,
orgId: 19,
page: 2,
length: 12,
requestId: 5432,
campaignId: 3215,
startDate: '05/02/25',
endDate: '06/24/15',
filterPath: '/:account/',
filterRegion: 'North Amarica',
webSiteId: 4,
message: { message: "this is my campaign post" },
buyRequestId: 5423
};
beforeEach(function () {
mockApiResourceProvider = {
hasError: false,
get: function (url, params) {
return {
then: function (callback, errorCallback) {
if (!mockApiResourceProvider.hasError) return callback(mockAccount);
return errorCallback();
}
};
},
post: function (url, params, data) {
return {
then: function (callback, errorCallback) {
if (!mockApiResourceProvider.hasError) return callback(data);
return errorCallback();
}
};
},
put: function (url, params, data) {
return {
then: function (callback, errorCallback) {
if (!mockApiResourceProvider.hasError) return callback(data);
return errorCallback();
}
};
},
delete: function (url, params) {
return {
then: function (callback, errorCallback) {
if (!mockApiResourceProvider.hasError) return callback();
return errorCallback();
}
};
}
};
module(function ($provide) {
$provide.value('apiResource', mockApiResourceProvider);
});
inject(function ($injector) {
webSiteBuyRequestService = $injector.get('webSiteBuyRequestService');
});
});
describe('cancelWebSiteBuyRequest() function', function () {
var baseURL = '/:orgId/WebSites/:webSiteId/BuyRequests/:requestId/Cancel';
var baseCall = { orgId: mockAccount.orgId, webSiteId: mockAccount.webSiteId, requestId: mockAccount.requestId };
it("with no error", function () {
spyOn(mockApiResourceProvider, "put").and.callThrough();
var result = webSiteBuyRequestService.cancelWebSiteBuyRequest(mockAccount.orgId, mockAccount.webSiteId, mockAccount.requestId, mockAccount.message);
expect(mockApiResourceProvider.put).toHaveBeenCalledWith(baseURL, baseCall, mockAccount.message);
expect(result.$$state.status).toEqual(1);
expect(result.$$state.value).toEqual(mockAccount.message);
});
});
Also if I change the code to use mockAccount.message.message it gives me the error
Expected spy put to have been called with [ >'/:orgId/WebSites/:webSiteId/BuyRequests/:requestId/Cancel', { orgId : 19, >webSiteId : 4, requestId : 5432 }, 'this is my campaign post' ] but actual >calls were [ '/:orgId/WebSites/:webSiteId/BuyRequests/:requestId/Cancel', { >orgId : 19, webSiteId : 4, requestId : 5432 }, { message : 'this is my campaign >post' } ].
Your product code is wrapping an object around the message you are sending in:
, { message: message }
You are then sending mockAccount.message as a parameter. So you end up with:
{ message: { message: 'this is my campaign post' }};
I think you want to send in mockAccount.message.message (just the text):
it("with no error", function () {
spyOn(mockApiResourceProvider, "put").and.callThrough();
var result = webSiteBuyRequestService.cancelWebSiteBuyRequest(mockAccount.orgId, mockAccount.webSiteId, mockAccount.requestId, mockAccount.message.message);
Then, inside the production code, you will wrap the text and produce:
{ message: 'this is my campaign post' }
Which will then match mockAccount.message;
Related
i want to get the object from my collection based on the quesListName which i send as a param to the server
here is my service
angular.module('hrPortalApp')
.service('getCandidateInterviewListService', function($http, ajaxServiceManager) {
var sUrlQuestions = "http://localhost:4000/onboardvue/questions/qListQuestions/";
return {
fnGetQuestions: function(qListName) {
return ajaxServiceManager.fnQuery({
sUrl: sUrlQuestions,
sMethod: "GET",
oData: null,
oParams: {
quesListName: qListName
}
});
},
};
});
below is my schema
var QuestionsSchema = new Schema({
topicName: String,
quesListName: String,
question:String
});
and the query which i wrote to get the object based on quesListName is
exports.query = function(req, res) {
Questions.find({quesListName:req.query.quesListName}, function(err, questions) {
if (err) {
return handleError(res, err);
}
return res.status(200).json(fnData(questions));
});
};
but i am getting 500 error
I'm trying to implement an autocomplete feature using Elasticsearch, angularJS and bootstrap.
I've got inspired by this solution :
autocomplete/typeahead angularjs bootstrap on elasticsearch
This is my Angular code:
angular.module('cineAngularApp')
.service('client', function (esFactory) {
return esFactory({
host: 'localhost:9200',
apiVersion: '2.2',
log: 'trace'
});
});
angular.module('cineAngularApp')
.controller('AutocompleteCtrl', function ($scope,client) {
$scope.getResult = function(val){
return client.search({
index: 'autocomplete_test',
fields: 'city',
q: 'city:'+val
}).then(function (resp) {
var keywords = [];
for(var i in resp.hits.hits){
var fields = (resp.hits.hits[i]).fields["city"];
keywords.push(fields);
}
return keywords;
}, function (err) {
console.trace(err.message);
});
};
});
Here is my problem
The above code works fine when I use a simple query, but as soon as I change the query by adding body it doesn't work.
angular.module('cineAngularApp')
.controller('AutocompleteCtrl', function ($scope,client) {
$scope.getResult = function(val){
return client.search({
index: 'autocomplete_test',
fields: 'city',
body: {
query: {
match: {
city: val
}
}
}
}).then(function (resp) {
var keywords = [];
for(var i in resp.hits.hits){
var fields = (resp.hits.hits[i]).fields["city"];
keywords.push(fields);
}
return keywords;
}, function (err) {
console.trace(err.message);
});
};
});
I don't know if it can help but I've also noticed when debugging that it's not a POST request anymore but it's an OPTION one.
Thanks in advance for your help.
Try with this:
return client.search({
index: 'movies',
"fields": [ "title" ],
"body": { // Use body field on elasticsearch client library
"query": {
"query_string": {
"fields": ["title"],
"query": "title:"+val
}
}
}
}).then(function (resp) {
// ....
})
I have a service class in angular that calls my backend and gets a userInfo as an object. My angular service class has the following.
var userResource = $resource(coreURL+'getFullProfile', {}, {
getUserInfo: {
method: 'POST'
}
userService.getUserInfo = function (userObj) {
var res = userResource.getUserInfo();
var promises = res.$promise;
return promises;
}
My controller class has the following.
promise = userService.getUserInfo();
promise.then(function (response) {
$scope.user = response;
});
My backends service returns an object.
My problem is I get the user info Object from backend but its not properly wrapped inside a object.the object is mix up with some angular variables. I dont have a response.data .the response object itself has all the information.
$promise: Objectcatch: function (callback) {finally: function (callback) {then: function (callback, errback, progressback) {__proto__:
Object
$resolved: true
about: "sdadsf"
country: "India"
creationDate: "2015-04-07"
email: "user3"
id: 3
industries: Array[2]
name: "user3"
phoneNo: 0
progressLevel: 1
The above response contains $promise and $resolved combined in my object. how can I get my data separately as an object.
controller.js
(function () {
var userController;
userController = function ($scope, userService, searchService) {
var delegate;
var masterUser;
$scope.user = {};
$scope.newEducation = [];
$scope.newProfession = [];
$scope.editMode=false;
$scope.hospitals=[];
$scope.yearOptions={
'year-format': "'yy'",
'starting-day': 1,
'datepicker-mode':"'year'",
'min-mode':"year"
};
$scope.hospit=function(){
promise = userService.getHospitals();
promise.then(function (response) {
$scope.hospitals = response.data;
});
};
delegate = {
getUserInfo: function () {
userService.getUserInfo(this.onGetUserData,this.onGetError);
},
onGetUserData :function(data){
var usr = (new dcuser(data));
$scope.user = usr;
$scope.masterUser = angular.copy(usr);
},
onGetError :function(data){
alert("error");
},
saveUserInfo:function(){
alert('saveUserInfo');
userService.saveUserInfo($scope.user,this.onSaved);
},
onSaved:function(){
$scope.editMode=false;
},
enableEdit:function(){
$scope.editMode = true;
},
cancelEdit:function(){
angular.copy($scope.masterUser, $scope.user);
$scope.editMode = false;
delegate.getUserInfo();
},
getIndustries :function(){
alert("getIndustries");
},
searchHospitals :function(){
searchService.searchHospitals("a",this.onGetHospitals);
},
onGetHospitals :function(data){
$scope.hospitals = data;
},
searchMedicalSchools :function(){
searchService.searchMedicalSchools("a",this.onGetMedicalSchools);
},
onGetMedicalSchools :function(data){
$scope.medicalSchools = data;
},
connectUser:function(user){
alert("connectUser");
userService.connectUser(user,this.onConnectSuccess,this.onGetError);
},
onConnectSuccess:function(){
alert("connection request sent");
},
initProfieCompletion: function(){
alert("in");
$scope.user.profession = [];
$scope.user.profession.push({
"hospital": "as",
"speciality": "as",
"fromDate": "",
"toDate": ""
});
promise = userService.getHospitals();
promise.then(function (response) {
$scope.hospitals = response.data;
});
},
addEducation:function(){
$scope.newEducation.push({
"medicalSchool": "",
"speciality": "",
"degree": "",
"graduatedYear": ""
});
},
addProfession:function(){
$scope.newProfession.push({
"hospital": "",
"speciality": "",
"fromDate": "",
"toDate": ""
});
}
};
return $scope.delegate = delegate;
}
dc.userModule.controller('userController', userController);
}).call(this);
service.js
(function () {
"use strict";
dc.app.service('userService', ['$rootScope','$resource', '$http', function ($rootScope,$resource, $http) {
var userService = {};
var coreURL = $rootScope.coreURI+'user/';
var userResource = $resource(coreURL+'getFullProfile', {}, {
getUserInfo: {
method: 'GET'
},
saveUserInfo: {
method: 'POST',
url: coreURL+'updateUserInfo'
}
});
var connectResource = $resource(coreURL + 'connectRequest',{}, {
connectUser: {
method: 'POST'
}
});
var userPhotoResource = $resource(coreURL + 'uploadPhoto', {}, {
uploadPhoto: {
method: 'POST'
}
});
userService.getUserInfo = function (onSuccess,onFailure) {
return(userResource.getUserInfo(onSuccess,onFailure));
},
userService.saveUserInfo = function(user,onSuccess){
return userResource.saveUserInfo(user,onSuccess);
},
userService.connectUser = function(user,onSuccess,onFailure){
return connectResource.connectUser(user,onSuccess,onFailure);
},
userService.uploadPhoto =function(image){
var promises = userPhotoResource.uploadPhoto(image);
return promises;
},
userService.getHospitals = function(){
alert('ser');
var promises = $http.get('dcResources/hospitals.json');
return promises;
}
return userService;
}]);
}).call(this);
I tried to create an item on the API and return a value with new 'ScheduleID', When I did a trace, API does return a new ScheduleID in the newly created object, but ScheduleID is never saved in the dataSource. Anyone know why?
vm.schedulerOptions = {
date: new Date(classStartDate.getUTCFullYear(), classStartDate.getUTCMonth(), classStartDate.getUTCDate(), 0, 0, 0),
height: 600,
views: [
"day",
{type: "week", selected: true},
],
dataSource: {
transport: {
read: function (options) {
if ($stateParams.classId) {
scheduleDf.getScheduleByClassId($stateParams.classId).success(function (result) {
options.success(result);
}).error(function (err) {
options.error(err);
})
} else if ($stateParams.sectionId) {
scheduleDf.getScheduleBySectionId($stateParams.sectionId).success(function (result) {
options.success(result);
}).error(function (err) {
options.error(err);
})
}
},
create: function (options) {
options.data.ClassId = classInfor.data[0].ClassID;
options.data.AtLocationId = vm.locationCb.dataItem().LocationID;
options.data.ConfirmationNumber = vm.ConfirmationNumber;
scheduleDf.createSchedule(options.data).success(function (result) {
//vm.grid.dataSource.read();
options.success(result);
}).error(function (err) {
options.error(err);
})
},
update: function (options) {
if (!fromMovingBar) {
options.data.AtLocationId = vm.locationCb.dataItem().LocationID;
fromMovingBar = false;
}
scheduleDf.updateSchedule(options.data).success(function (result) {
vm.grid.dataSource.read();
options.success(result);
}).error(function (err) {
options.error(err);
})
},
destroy: function (options) {
scheduleDf.deleteSchedule(options.data.ScheduleID).success(function (result) {
vm.grid.dataSource.read();
options.success();
}).error(function (err) {
options.error(err);
})
}
},
schema: {
model: {
id: "ScheduleID",
fields: {
start: {type: "date", from: "FromTime"},
end: {type: "date", from: "ToTime"}
}
}
}
},
editable: {
template: '<div ng-include="' + "'/schedule/_schedule_editor.html'" + '"></div>',
create: false
},
edit: function (e) {
e.container.data("kendoWindow").center();
e.container.find(".k-edit-form-container").width("auto");
e.container.data("kendoWindow").wrapper.css({width: 700});
},
moveEnd: function (e) {
fromMovingBar = true;
},
resizeEnd: function (e) {
fromMovingBar = true;
},
resources: [{
field: 'SessionTypeID',
dataColorField: 'ColorCode',
dataValueField: 'SessionTypeID',
dataTextField: 'SessionTypeName',
dataSource: sessionTypes.data
}]
};
The reason for current behavior is that the response from the server is not formatted the same way as the "read" request. You should try to insert the record inside array. For more info you can check this help article.
Also I notice that the Scheduler have no timezone option set. Please note that the timezone option is highly recommended to be set - for more details you can check the new Timezones help article.
I have following service method with return statement.
this.partnersListForAutocomplete = function (container, options) {
$("#autocompletePartners").kendoAutoComplete({
dataSource : {
type: "json",
serverFiltering: true,
transport: {
read: function (options) {
console.log("List");
console.log(options.data);
requestParams = {
"entityName": "dvd",
"page": 1,
"pageSize": 20,
"filter": options.data.filter,
"sort": [
{
"field": "name",
"ord": "asc"
}
]
};
ApiService.doHttpRequest(
"POST",
$rootScope.apiBaseUrl + "partner/search",
requestParams
)
.success(function (data, status, headers, config) {
})
.error(function (data, status, headers, config) {
});
}
}
},
dataTextField: "name" ,
dataValueField: "id",
filter: "contains",
minLength: 1,
change : function (e) {
// I WANT RETURN IT
return "test";
},
select : function (e) {
// I WANT RETURN IT
return "test";
}
});
};
Which is called by this code from controller method:
selectedPartnerId = GlobalHelperService.partnersListForAutocomplete();
$scope.projectDetail.test = selectedPartnerId;
Problem is that returned value is not passed into selected scope.
How can i solve it please?
Note: Method for autocomplete is assync.
Thanks for any help.
You have a couple of options that I can think of from the top of my head:
You could return a promise from the partnersListForAutocomplete() method, and then inside your controller you would then do something like the following pseudocode:
GlobalHelperService.partnersListForAutocomplete()
.then(function(response) {
$scope.projectDetail.test = response;
});
Or, accept a callback to your partnersListForAutocomplete() method, and then inside your controller you would then do something like the following pseudocode:
GlobalHelperService.partnersListForAutocomplete(function(response) {
$scope.projectDetail.test = response;
});