I developed a table for my notefrais, but the problem is when I add notefrais, the table doesn't refresh automatically. Is it necessary to refresh the page to display the new notefrais? How can I modify my code to refresh this table automatically? (I work with angular)
The error:
ERROR Error: Uncaught (in promise): TypeError: Cannot read property
'draw' of undefined TypeError: Cannot read property 'draw' of
undefined
async ngOnInit() {
let id = localStorage.getItem('userId');
...
...
this.notes = await this._dashbordService.getNotes(id);
...
setTimeout(function () {
this.table = $('#example-table').DataTable({
pageLength: 2,
"bLengthChange": false,
});
}, 1000);
}
async processAdd() {
let nf = new NoteDeFrais();
let frm = this.addfrm.value;
nf.UserId = this.userId;
...
...
this._dashbordService.addNoteFrais(nf);
this.refreshTable(); // for refresh table after add notefrais but don't work !
}
async refreshTable() {
let id = localStorage.getItem('userId');
this.notes = await this._dashbordService.getNotes(id);
this.table.draw(); // the same problem for this.table.reload()
}
Related
I am trying to integrate google-recaptcha but no success.
Getting error
feedback.js:39 Uncaught TypeError: grecaptcha.render is not a function
main.js
'googlerecaptcha':'https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit',
define(['ojs/ojcore', 'knockout', 'jquery', 'appController', 'ckeditor', 'googlerecaptcha', 'ojs/ojlabel',
'ojs/ojknockout', 'ojs/ojinputtext', 'ojs/ojformlayout'],
function (oj, ko, $, app, ckeditor, grecaptcha) {
/**
* The view model for the main content view template
*/
function feedbackViewModel() {
var self = this;
// For small screens: labels on top
// For medium screens and up: labels inline
this.labelEdge = ko.computed(function () {
return app.smScreen ? "top" : "start";
}, this);
onloadCallback = function (a) {
grecaptcha.render('submit', {
'sitekey': 'YOUR_API_KEY',
'callback': self.onSubmit
}, true);
};
this.handleActivated = function (info) {
};
self.onSubmit = function (token) {
console.info("google recatpcha onSubmit", token)
//do validation/application code using token
var data = {secret: grecaptcha, response: recaptchaToken};
$.post({
url: "https://www.google.com/recaptcha/api/siteverify",
form: data
}).then(function (e) {
//recaptcha service called...check result
var resp = JSON.parse(e);
if (resp.success == false) {
console.info("recaptcha token outcome is false")
} else {
console.info("recaptcha token validated")
}
});
};
}
return feedbackViewModel;
});
Do you have a mapping for 'googlerecaptcha' in src/js/path_mapping.json? If I go to https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit, I do not see that it is returning any valid object. So most likely 'grecaptcha' variable is undefined.
reCaptcha + RequireJS
Looks like reCaptcha is a function that has to be executed vs an object that can be interacted with directly. So you may need a different approach, something mentioned in this thread.
I am trying to extract a URL from a registration email in my end-to-end test for Protractor, but I am getting errors trying to parse the larger string.
The error I am getting is:
*
Failures: 1) MockMock Get verification link Message:
Failed: regText.indexOf is not a function Stack:
TypeError: regText.indexOf is not a function
at getRegLink (D:\QA\Scripting\ProtractorHelloWorld\CCspecMockMock.js:19:27)
at UserContext. (D:\QA\Scripting\ProtractorHelloWorld\CCspecMockMock.js:37:14)
at C:\Users\dcoughler\AppData\Roaming\npm\node_modules\protractor\node_modules\jasminewd2\index.js:112:25
at new ManagedPromise (C:\Users\dcoughler\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:1077:7)
at ControlFlow.promise (C:\Users\dcoughler\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:2505:12)
at schedulerExecute (C:\Users\dcoughler\AppData\Roaming\npm\node_modules\protractor\node_modules\jasminewd2\index.js:95:18)
at TaskQueue.execute_ (C:\Users\dcoughler\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:3084:14)
at TaskQueue.executeNext_ (C:\Users\dcoughler\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:3067:27)
at asyncRun (C:\Users\dcoughler\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:2974:25)
at C:\Users\dcoughler\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:668:7
From: Task: Run it("Get verification link") in control flow
at UserContext. (C:\Users\dcoughler\AppData\Roaming\npm\node_modules\protractor\node_modules\jasminewd2\index.js:94:19)
at C:\Users\dcoughler\AppData\Roaming\npm\node_modules\protractor\node_modules\jasminewd2\index.js:64:48
at ControlFlow.emit (C:\Users\dcoughler\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\events.js:62:21)
at ControlFlow.shutdown_ (C:\Users\dcoughler\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:2674:10)
at shutdownTask_.MicroTask (C:\Users\dcoughler\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:2599:53)
From asynchronous test:
Error
at Suite. (D:\QA\Scripting\ProtractorHelloWorld\CCspecMockMock.js:35:1)
at Object. (D:\QA\Scripting\ProtractorHelloWorld\CCspecMockMock.js:2:1)
at Module._compile (internal/modules/cjs/loader.js:688:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
at Module.load (internal/modules/cjs/loader.js:598:32)
at tryModuleLoad (internal/modules/cjs/loader.js:537:12) 1 spec, 1 failure Finished in 0.622 seconds
*
Here is the code:
// spec.js
describe('MockMock', function() {
var tRegMessage = element(by.className('well'));
var tabledata = $$('./table');
// get rows
var rows = tabledata.all(by.tagName("tr"));
// get cell values
var cells = rows.all(by.tagName("td"));
var commonfunctions = require('./CCCommonFunctions.js');
function clickRegistration(email) {
element(by.xpath("//td[. = '" + email + "']/following-sibling::td/a")).click();
}
function getRegLink(regText) {
var startUrl = regText.indexOf("http://");
var endUrl = regText.indexOf("Thank you",startUrl);
getRegLink = regText.substring(startUrl,endUrl);
}
function Login(username, password) {
fUserName.sendKeys(username);
fPassword.sendKeys(password);
commonfunctions.ccClick(bLoginButton);
}
beforeEach(function() {
browser.waitForAngularEnabled(false);
browser.get('http://ns-rd-app-wi:2525/');
});
it('Get verification link', function() {
clickRegistration('PhillipPies#mock.com');
browser.get(getRegLink(tRegMessage));
browser.pause();
});
});
How should I be parsing strings in protractor? I'm too used to vbscript, it seems.
==================================================================
I've made changes based on the comments below, but I am still stuck:
describe('MockMock', function() {
var tRegMessage = element(by.className('well'));
var tabledata = $$('./table');
// get rows
var rows = tabledata.all(by.tagName("tr"));
// get cell values
var cells = rows.all(by.tagName("td"));
var commonfunctions = require('./CCCommonFunctions.js');
function clickRegistration(email) {
element(by.xpath("//td[. = '" + email + "']/following-sibling::td/a")).click();
}
function getRegLink(regMessage) {
return new Promise(resolve => {
regMessage.getText().then(text => {
var startUrl = text.indexOf("http://");
var endUrl = text.indexOf("Thank you",startUrl);
resolve(text.substring(startUrl,endUrl-2))
} )
})
}
beforeEach(function() {
browser.waitForAngularEnabled(false);
browser.get('http://ns-rd-app-wi:2525/');
});
it('Get verification link', function() {
clickRegistration('PhillipPies#mock.com');
var regURL=getRegLink(tRegMessage.getText());
browser.get(regURL.toString());
browser.pause();
});
});
This gives a new error now:
Failed: unknown error: unhandled inspector error: {"code":-32000,"message":"Cannot navigate to invalid URL"}
(Session info: chrome=71.0.3578.98)
(Driver info: chromedriver=2.46.628402 (536cd7adbad73a3783fdc2cab92ab2ba7ec361e1),platform=Windows NT 10.0.16299 x86_64)
You got error on line:
browser.get(getRegLink(tRegMessage));
Because tRegMessage is not string. It is ElementFinder (you got it from this line element(by.className('well'));)
So, you need take a text from this element. For example:
it('Get verification link', function() {
const url = tRegMessage.getText();
clickRegistration('PhillipPies#mock.com');
browser.get(getRegLink(url));
browser.pause();
});
Also, your method getRegLink() does not return string. So, after first fix you will get an error that browser.get() should have argument string
The problem is tRegMessage is not a string. It's an ElementFinder. You need to call getText() first.
function getRegLink(regMessage) {
return new Promise(resolve => {
regMessage.getText().then(text => {
var startUrl = text.indexOf("http://");
var endUrl = text.indexOf("Thank you",startUrl);
resolve(text.substring(startUrl,endUrl));
}
}
}
Quite an old thread but might as well give it an answer.
The original response was updated, the error is now that .getText() is called twice.
Here
var regURL=getRegLink(tRegMessage.getText());
and then here:
regMessage.getText().then(text => {
To fix your error you need to remove one of these getText() (ideally remove the first one I quoteed so all Promise stuff happens in the functions).
Then you could change your function to return the Promise instead of creating a new one:
function getRegLink(regMessage) {
return regMessage.getText().then(text => {
var startUrl = text.indexOf("http://");
var endUrl = text.indexOf("Thank you",startUrl);
return text.substring(startUrl,endUrl-2);
});
}
I have a react component - coursePage.js
function getCourseInitState(){
return {
courses: CourseStore.getAllCourses()//courseStore is required in script
};
}
var Courses = React.createClass({
getInitialState: function(){
return getCourseInitState();
},
render: function () {
return (
<div>
<h1> Course </h1>
<CourseList courses={this.state.courses} />
</div>
);
}
});
Action file -courseAction
var CourseAction = {
CourseList: function(){
var courseList = CourseApi.getAllCourses();
Dispatcher.dispatch({
actionType: ActionTypes.COURSE_INITIALIZE,
courseList: courseList
});
}
Store File - courseStore
var CourseStore = assign({}, EventEmitter.prototype, {
addChangeListener: function(callback){
this.on(CHANGE_EVENT, callback);
},
removeChangeListener: function(callback){
this.removeListener(CHANGE_EVENT, callback);
},
emitChange: function(){
this.emit(CHANGE_EVENT);
},
getAllcourses: function(){ //here is the function define
return _courses;
},
getCourseById: function(id){
return _.find(_courses, {id: id});
}
});
Dispatcher.register(function(action){
switch(action.actionType){
case ActionTypes.COURSE_INITIALIZE:
_courses = action.CourseList;
CourseStore.emitChange();
break;
}
});
module.exports = CourseStore;
in console I am getting "Uncaught TypeError: CourseStore.getAllCourses is not a function"
I don't want to call api directly in my coursePage.js so I find this way of initialising the page but it is not working.
(Please note - I am new to this) As per my recent learning Action file must always call API and send the request to State. I can load with help of componentWillMount function. But, I wanted to solve with this.If not wrong, then it is more neat and preferable way of implementing?
You have a typo -> getAllcourses in the Store and in the Component you call getAllCourses
getAllCourses: function(){ //Should be getAllCourses instead of getAllcourses
return _courses;
},
I have a viewmodel and there I have properties which are extended to use validation. I call ko.validation.group(self) but this doesn't add the isValid() method to the viewmodel.
So I get an error that isValid() is undefined.
Here is my code:
var brechtbaekelandt = brechtbaekelandt || {};
brechtbaekelandt.login = (function ($, jQuery, ko, undefined) {
"use strict";
function LoginViewModel() {
var self = this;
self.userName = ko.observable();
self.password = ko.observable();
self.rememberMe = ko.observable();
self.errorMessage = ko.observable();
self.userName.extend({ required: { message: 'Please enter your username' } });
self.password.extend({ required: { message: 'Please enter your password' } });
self.errors = ko.validation.group(self);
};
LoginViewModel.prototype.login = function () {
var self = this;
self.errorMessage(null);
alert('entering login');
// self.isValid() is not a function
if (!self.isValid()) {
alert('login invalid');
self.errors.showAllMessages();
return;
}
else
{
alert('login valid');
// do login
}
};
function init() {
alert('entering init');
var knockoutValidationSettings = {
insertMessages: false,
decorateElement: true,
decorateElementOnModified: true,
decorateInputElement: true,
//errorMessageClass: 'error',
//errorElementClass: 'error',
//errorClass: 'error',
errorsAsTitle: false,
parseInputAttributes: false,
messagesOnModified: true,
messageTemplate: null,
grouping: { deep: true, observable: true }
};
ko.validation.init(knockoutValidationSettings, true);
var viewModel = new LoginViewModel();
ko.applyBindingsWithValidation(viewModel);
}
return {
LoginViewModel: LoginViewModel,
init: init
};
})($, jQuery, ko);
I have created a js fiddle: click here
I've read somewhere that you need to call registerExtenders() but I tried it and it doesn't work either.
Can someone help me in the right direction? Thx!
well you seem to be looking for isValid when using group tough there is a way (alternate way) using length property to achieve it . As isValid doesn't seem to be available when using group (it exists with validatedObservable) .
As #jeff mentioned in one of this answers on this topic
The ko.validation.group just gives you an (computed) observable of all
the error messages in a model. It only collects error messages of
direct properties of the model.
The ko.validatedObservable on the other hand not only collects the
error messages, but also wraps the model in an observable and adds an
isValid property which indicates whether or not there are any error
messages (i.e., the model was completely valid). Otherwise, they're
essentially the same.
I modified your code accordingly like below
self.errors = ko.validation.group(self); //It will group error messages in array i.e based on count you must validate
LoginViewModel.prototype.login = function () {
var self = this;
self.errorMessage(null);
//self.isValid() doesn't exist here . so you should base length
if (self.errors().length>0) {
alert('login invalid');
self.errors.showAllMessages();
return;
}
};
working sample with group
working sample with ValidatedObservable Preferable way Imho
Having problem with prototype ajax and setTimeout. Here is my code shortened:
//new ajax request
....onComplete: function (transport) { //json as this -> array[$i].something
var json = transport.responseJSON;
var $i = 0;
window.setTimeout(function () {
SLOW();
},
500); //display every json[$i] with custom delay
function SLOW() {
$i++;
if (json[$i].something !== null) { //insert in proper div id in the html document
window.setTimeout(function () {
$('document_div' + json[$i].something).innerHTML = json[$i].something_to_display;
},
500);
window.setTimeout(function () {
$('document_div' + json[$i].something).innerHTML = json[$i].something_to_display;
},
1000);...window.setTimeout(function () {
SLOW();
},
500);
} else {
//stop and continue
}
Getting this error: json[$i] is undefined.
EDIT: looks like i'm getting this error on second timeout, the first one changes the div correctly.
Done.
Solution was to re-var json again before using it in setTimeout.
var json_something = json[$i].something; //and so on...
var json_something_to_display = json[$i].something_to_display
window.setTimeout(function() { $('document_div'+json_something).innerHTML = json_something_to_display; }, 500);
Can somebody explain why this is needed? Why varing json is not enough and it disapears somewhere after one window.setTimeout function?