dateObj.getMonth() not working in nativescript - nativescript

I am trying to get the month from the date object . But I am getiing error whci displays says "getMonth is not a function".
Since I saw some Java script tutorials , where getMonth() is supported in ES6.
Am I missing importing anything.
var config = require("../../shared/config");
var fetchModule = require("fetch");
var ObservableArray = require("data/observable-array").ObservableArray;
var datePickerModule = require("tns-core-modules/ui/date-picker");
function TaskListViewModel(items){
var listModel = new ObservableArray(items);
listModel.getTaskList = function()
{
return fetchModule.fetch(config.TaskListURL,{
method:"Get"
})
.then(handleErrors)
.then(function(response){
return response.json();
}).then(function(data) {
data.forEach(function(element) {
var dateObj = Date.parse(element.followUpDate)
listModel.push({
fallowUpDateMonth:dateObj.getMonth(),
faloowUpDateDay:dateObj.getDate(),
fallowupDateYear:dateObj.getFullYear(),
});
});
});
};
return listModel;
}
module.exports = TaskListViewModel;

Related

Jasmine: Expected spy <function> to have been called error

In my angular application, I am trying to write a test case for following scenario but getting error 'Expected spy reinvite to have been called.'. Im testing on "jasmine-core: ^2.5.2 and "karma: ^1.3.0". I have written similar test cases and they passed without error.
In my controller file:
function reinvite() {
var emailsToReInvite = $j.map($scope.settingsData.userSettingsDetails, function(user) {
if(user.reInviteChecked){
return user.email;
}
});
if (emailsToReInvite.length >= 1) {
var invitation = { invitees: emailsToReInvite, listId: listId};
invitation = JSON.stringify(invitation);
inviteCollaboratorsModalDataService.reinvite(invitation).then(
function success(response) {
if(response.data.messages[0].code == 214){
$scope.showReinviteSuccess = true;
}
}else{
$scope.showReinviteSuccess = false;
}
}
);
}
}
And my spec file:
describe('settingsModalController', function() {
var controllerUnderTest = "settingsModalController";
var controllerResolver, rootScope, injector, $scope, inviteCollaboratorsModalDataService
beforeEach(function(){
angular.mock.module('sharedListApp');
inject(function($controller, $rootScope, $injector){
controllerResolver = $controller;
rootScope = $rootScope;
injector = $injector;
});
$scope = rootScope.$new();
inviteCollaboratorsModalDataService = injector.get('uiCommon.inviteCollaboratorsModalDataService');
});
it("should send re-invitation mail to selected users successfully", shouldReinviteSelectedUsers);
function shouldReinviteSelectedUsers() {
var $q = injector.get('$q');
$scope.settingsData = {
userSettingsDetails: [{email: 'abc#xyz.com'}]
};
var data = {
messages: [ { code: 214 }],
invite: {
invitation: $scope.settingsData
}
};
var response = { data: data };
var mockResult = new $q.defer();
mockResult.resolve(response);
spyOn(inviteCollaboratorsModalDataService, 'reinvite').and.returnValue(mockResult.promise);
controllerResolver(controllerUnderTest, { $scope: $scope });
$scope.reinvite();
$scope.showReinviteSuccess = true;
$scope.$apply();
expect(inviteCollaboratorsModalDataService.reinvite).toHaveBeenCalled();
expect($scope.showReinviteSuccess).toBe(true);
}
}
What am i doing wrong or what am i missing? Thanks in advance.
Ok, so i missed one variable to add in $scope.settingsData in my spec file which was why my spec code was not parsing into the first 'if' loop of the controller. Got it working by adding 'reInviteChecked: true' in:
$scope.settingsData = {
userSettingsDetails: [{email: 'abc#xyz.com', reInviteChecked: true}]
};

ioredis bluebird a promise was created in a handler but was not returned from it

Can someone please explain to me why i'm getting this warning Warning: a promise was created in a handler but was not returned from it when I execute the following code:
cache['deviceSlave'].getBySystemId(systemId).then(function(slavesMapping) {
// do other stuff
}).catch(function(err) {
// throw error
});
Here is the rest of the code:
var Promise = require('bluebird');
var _ = require('lodash');
var Redis = require('ioredis');
var config = require('/libs/config');
var redis = new Redis({
port: config.get('redis:port'),
host: config.get('redis:host'),
password: config.get('redis:key'),
db: 0
});
var self = this;
module.exports.getBySystemId = function(systemId) {
return new Promise(function(resolve, reject) {
var systemIds = [systemId];
self.getBySystemIds(systemIds).then(function(result) {
return resolve(_.values(result)[0]);
}).catch(function(err) {
return reject(err);
});
});
};
module.exports.getBySystemIds = function(systemIds) {
return new Promise(function(resolve, reject) {
var pipeline = redis.pipeline();
_.each(systemIds, function(systemId) {
var cacheKey = 'device_slaves:' + systemId.replace(/:/g, '');
// get through pipeline for fast retrieval
pipeline.get(cacheKey);
});
pipeline.exec(function(err, results) {
if (err) return reject(err);
else {
var mapping = {};
_.each(systemIds, function(systemId, index) {
var key = systemId;
var slaves = JSON.parse(results[index][1]);
mapping[key] = slaves;
});
return resolve(mapping);
}
});
});
};
I'm using the following libraries: ioredis & bluebird.
The code executes fine and everything just works good! I just dont like the fact I get an warning which I can not solve!
Bluebird is warning you against explicit construction here. Here is how you should write the above code:
module.exports.getBySystemId = function(systemId) {
return self.getBySystemIds([systemId]).then(result => _.values(result)[0]);
};
There is no need to wrap the promise - as promises chain :)

errors creating test for passport using mocha

I've been working a while on getting a test to work with Mocha and Passport. I tried a couple articles on here, but I can't get them to work.
Currently, I have installed supertest and I'm trying that.
process.env.NODE_ENV = 'test';
var chai = require('chai');
var chaiHttp = require('chai-http');
var app = require('../app');
//var request = require('supertest')//(app);
//var server = request.agent(app);
//var Strategy = require('passport-strategy');
var Strategy = require('passport-local').Strategy;
var m_ticket_data = require('../model/ticket');
var m_Kbase_data = require('../model/Kbase');
var m_KbaseScript_schema = require('../model/KbaseScript');
var should = chai.should();
var expect = chai.expect;
chai.use(chaiHttp);
chai.use(require('chai-passport-strategy'));
describe('Ticket', function() {
var user, info;
before(function(done) {
console.log("hello from strategy");
chai.passport.use( new Strategy(function(username, password, done){
console.log("hello from strategy2");
done(null, { id: '1234' }, { scope: 'read' });
}
))
.success(function(u, i) {
user = u;
info = i;
done();
})
.req(function(req) {
//req.headers.authorization = 'Bearer vF9dft4qmT';
})
.authenticate();
done();
});
it ('blankout the database', function(done){
m_ticket_data.remove({}, function(){
done();
});
});
it('looks for a blank from /ticket/all', function (done) {
chai.request('http://127.0.0.1:5000')
.get('/ticket/all')
.end(function (err, res) {
res.status.should.equal(200);
console.log(res.body);
//expect(res.body).to.deep.equal({});
done();
});
});
});
I can't create a temp user for testing, so I was thinking I was going to have to overwrite the authentication. However, I'm having a problem doing that. I found this npm (https://github.com/jaredhanson/chai-passport-strategy), and I'm trying this as the latest.
This is a test I created that works fine. I don't need to authenticate for it.
process.env.NODE_ENV = 'test';
var chai = require('chai');
var chaiHttp = require('chai-http');
var server = require('../app');
var m_Kbase_data = require('../model/Kbase');
var m_KbaseScript_schema = require('../model/KbaseScript');
var should = chai.should();
var expect = chai.expect;
chai.use(chaiHttp);
describe('KBasefull', function() {
m_Kbase_data.collection.drop();
it('need to add a kbase article for testing /KBase', function (done) {
chai.request('http://127.0.0.1:5000')
.post('/kbase')
.send({Problem: "Problem", description: "Description", resolution: "Something to fix"})
.end(function(err, res){
res.should.have.status(200);
done();
});
});
}

Knockout JS - update viewModel with AJAX Call

there are some similar questions but didn't help me to solve my issue. I can't update my results on page / view after updating my viewModel with AJAX. I am getting valid AJAX response that updates the view if I reload the page, but not when I click btnAdvancedSearch
I have simple HTML:
<div>
<input type="button" id="btnAdvancedSearch" data-bind="click: refresh" />
</div>
<div id="resultslist1" data-bind="template: { name: 'rest-template', foreach: restaurants }">
</div>
And I bind in on document load:
$(document).ready(function () {
ko.applyBindings(new RestaurantsListViewModel());
});
My viewModel is like this, and in it I call refresh that is bound with button
// Overall viewmodel for this screen, along with initial state
function RestaurantsListViewModel() {
var self = this;
self.restaurants = ko.observableArray([]);
var mappedRests = $.map($.parseJSON(sessionStorage.getItem('searchResults')), function (item) { return new Restaurant(item) });
self.restaurants = mappedRests;
self.refresh = function () {
updateRestaurantsList(); //Method executes AJAX and saves result to session.
var mappedRests2 = $.map($.parseJSON(sessionStorage.getItem('searchResults')), function (item) { return new Restaurant(item) });
self.restaurants= mappedRests2;
}
}
What am I missing here?
Thanks
I have tried waiting for AJAX to finish like this:
// Overall viewmodel for this screen, along with initial state
function RestaurantsListViewModel() {
var self = this;
self.restaurants = ko.observableArray([]);
var mappedRests = $.map($.parseJSON(sessionStorage.getItem('searchResults')), function (item) { return new Restaurant(item) });
self.restaurants = mappedRests;
self.refresh = function () {
var latitude = sessionStorage.getItem('latitude');
var longitude = sessionStorage.getItem('longitude');
var query = '{"Accepts_Reservations":"' + $('#chkReservation').is(":checked") + '","Accepts_Cards":' + $('#chkAcceptsCards').is(":checked") + '"}';
var searchResults = getRestaurantsAdvancedSearchAJAX(query, latitude, longitude, 40);
searchResults.success(function (data) {
var information = data.d;
var mappedRests2 = $.map($.parseJSON(information), function (item) { return new Restaurant(item) });
self.restaurants = mappedRests2;
});
};
};
Edit 1
Once you have declared your observable like so:
self.restaurants = ko.observableArray([]);
When you want to update restaurants you cannot do this:
self.restaurants = mappedRests2;
Instead, you need to do this:
self.restaurants(mappedRests2);
updateRestaurantsList(); //Method executes AJAX and saves result to session.
The comment after the above line indicates that this method is making an asynchronous call. Therefore, it is likely that the line after it is executing before sessionStorage has been populated. Maybe consider having updateRestaurantsList return a promise. Then you could update your code to something like this:
updateRestaurantsList().then(function() {
var mappedRests2 = $.map($.parseJSON(sessionStorage.getItem('searchResults')), function (item) { return new Restaurant(item) });
self.restaurants= mappedRests2;
});
This way the call to populate your mappedRests2 variable won't happen until after your updateRestaurantsList method has completed.
Edit 1
Be sure to never assign values to an observable using an equal sign.
// Overall viewmodel for this screen, along with initial state
function RestaurantsListViewModel() {
var self = this;
self.restaurants = ko.observableArray([]);
var mappedRests = $.map($.parseJSON(sessionStorage.getItem('searchResults')), function (item) { return new Restaurant(item) });
self.restaurants(mappedRests);
self.refresh = function () {
var latitude = sessionStorage.getItem('latitude');
var longitude = sessionStorage.getItem('longitude');
var query = '{"Accepts_Reservations":"' + $('#chkReservation').is(":checked") + '","Accepts_Cards":' + $('#chkAcceptsCards').is(":checked") + '"}';
var searchResults = getRestaurantsAdvancedSearchAJAX(query, latitude, longitude, 40);
searchResults.success(function (data) {
var information = data.d;
var mappedRests2 = $.map($.parseJSON(information), function (item) { return new Restaurant(item) });
self.restaurants(mappedRests2);
});
};
};

Why my model does not get synced?

I've written my first program with racer. It displays a simple text box manually bound to 'col.doc.prop' path. When I change the value, it does not apply to the store at server.
What causes my subscribed model not to get sync with server?
Server code:
var fs = require('fs');
var io = require('socket.io');
var racer = require('racer');
var mongo = require('racer-db-mongo');
racer.use(mongo);
racer.js({
entry: __dirname + '/client.js'
}, function(err, js) {
return fs.writeFileSync(__dirname + '/script.js', js);
});
var express = require('express');
var server = express.createServer();
server.use(express.static(__dirname));
server.get('/', function(req, res)
{
var model = store.createModel();
model.subscribe('col.doc', function(err, doc)
{
var prop = doc.get('prop');
if (!prop)
{
doc.set('prop', 123);
store.flush();
}
model.ref('_doc', doc);
model.bundle(function(bundle)
{
var client = require('fs').readFileSync('./client.html', 'utf-8');
client = client.replace('_init_', bundle.toString());
res.send(client);
});
});
});
var store = racer.createStore(
{
listen: server,
db:
{
type: 'Mongo',
uri: 'mongodb://localhost/racerdb'
}
});
store.set('col.doc.prop', 123);
store.flush();
server.listen(3001);
Client code:
useRacer = function()
{
var socket = io.connect('http://localhost:3001');
var racer = require('racer');
process.nextTick(function() {
racer.init(this.init, socket);
return delete this.init;
});
racer.on('ready', function(model)
{
addListener = document.addEventListener ? function(el, type, listener) {
return el.addEventListener(type, listener, false);
} : function(el, type, listener) {
return el.attachEvent('on' + type, function(e) {
return listener(e || event);
});
};
var element = document.getElementById('prop');
var listener = function()
{
var val = element.value;
model.set('col.doc.prop', val);
};
addListener(element, 'keyup', listener);
var upgrade = function(id, value)
{
if (model.connected)
{
var prop = model.get('col.doc.prop');
element.value = prop;
}
else
model.socket.socket.connect();
};
model.on('connectionStatus', upgrade);
model.on('set', 'con.*', upgrade);
});
};
The problem solved by changing some lines of the client code:
model.set('col.doc.prop', val) ==> model.set('_doc.prop', val)
model.get('col.doc.prop') ==> model.get('_doc.prop')
model.on('set', 'con.', upgrade) ==> model.on('set', '', upgrade)

Resources