Related
I am trying to render a template in onchange of a input field.
Here is the onchange method.
*.js
_onClickBasketInputChange: function(){
console.log('inside input change',this.basketVerificationId);
var self = this;
var barcode = $('.basket_barcode_input').val();
console.log('barcode',barcode);
// var rec = this._rpc({
return this._rpc({
model: 'mobile.basket.verification',
method: 'get_picking_details',
args: [this.basketVerificationId,barcode],
}).then(function(res){
// console.log('this',self);
console.log('picking_id',res);
var $body = this.$el.filter('.o_barcode_lines');// Here i am getting the error ' Uncaught (in promise) TypeError: this is undefined'
console.log('body',$body);
if (res['status'] == true){
console.log('successs');
var $lines = $(Qweb.render('basketVerificationLines', {
picking:res['picking_id'],
customer:res['partner_id'],
lines:res['line_ids']
}));
$body.prepend($lines);
}
// $('.basket_barcode_input').val('');
var message = res['result'];
if (res['status'] == false){
Dialog.alert(self, message);
}
});
},
But i am getting following error
Uncaught (in promise) TypeError: this is undefined
Update:
When change this to self, the value of $body is
body
Object { length: 0, prevObject: {…} }
length: 0
prevObject: Object { 0: div.o_action, length: 1 }
And the template not prepend to the body.
Please help to resolve this.
I got the solution,
I replace the .filter with .find then it works.
var $body = self.$el.find('.o_barcode_lines');
Can anyone help me? I'm really bad at programming
Error :Uncaught TypeError: datapoints.data.map is not a function at XMLHttpRequest.xmlhttp.onreadystatechange
const xmlhttp = new XMLHttpRequest();
const url = '//url//';
xmlhttp.open('GET', url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
const datapoints = JSON.parse(this.responseText);
//console.log(datapoints);
const labelsboy = datapoints.data.map(function(item){
return item.boy;
});
console.log(labelsboy);
}
}
file JSON API
{
"status": true,
"row": 2,
"data": {
"boy": 10,
"girl": 15
}
}
map is an array function but datapoints.data is an object. It seems like you are just trying to get one value from the object so you can just access it directly.
const labelsboy = datapoints.data.boy;
console.log(labelsboy);
I'm noob at front-end dev, but try to write tests for project.
Also, I'm using redux-saga and jest for testing
btw, I have saga:
export function* setAuthorizeCode(action) {
try {
let response = yield call(Api.token.getToken, action.payload.authorizeCode);
yield put(appActions.setAccessToken(response.data.access_token));
yield put(appActions.setIdToken(response.data.id_token));
const accessToken = yield select((state) => appSelectors.getAccessToken(state.app));
const idToken = yield select((state) => appSelectors.getIdToken(state.app));
response = yield call(Api.user.getUser, accessToken, idToken);
yield put(appActions.setUser(response.data));
} catch (error) {
console.log('Error: ', error);
}
}
function* setAuhtorizeCodeFlow () {
yield takeLatest(appActions.SET_AUTHORIZE_CODE, setAuthorizeCode);
}
export default function* authentication() {
yield all([
setAuhtorizeCodeFlow()
]);
}
And I'm write this test for this:
test('TESTING SAGAS', function(t) {
const gen = setAuthorizeCode()
let next = gen.next(appActions.setAuthorizeCode())
t.deepEqual(next.value, call(Api.token.getToken), 'must yield api.getToken')
next = gen.next(accessToken)
t.deepEqual(next.value, put(appActions.setAccessToken(accessToken)), 'must yield action appActions.setAccessToken')
next = gen.next(idToken)
t.deepEqual(next.value, put(appActions.setIdToken(idToken)), 'must yield action appActions.setIdToken')
next = gen.next()
t.deepEqual(next.value, select(accessToken), 'must select accessToken')
next = gen.next()
t.deepEqual(next.value, select(idToken), 'must select idToken')
next = gen.next(Api.user.getUser())
t.deepEqual(next.value, call(Api.user.getUser), 'must yield api.getUser')
next = gen.next(setUser)
t.deepEqual(next.value, put(appActions.setUser(setUser)), 'must yield appActions.setUser')
t.end()
})
I really don't know what is wrong.
But it's doesn't work, please I need some help, what am I doing wrong?
There is errors:
operator: deepEqual
expected: |- { '##redux-saga/IO': true, CALL: { context: null, fn:
[Function: getToken], args: [] } }
actual: |- undefined
And other 2 are the same.
I'm quiet new into testing and I don't seem to succeed to succesfully stub a function. I'm trying to stub the connection to the database, but it keep's contacting it, instead of using the result from the stub:
Here's the function:
var self = module.exports = {
VerifyAuthentication: function (data){
var deferred = q.defer()
if(typeof(data.email)=='undefined'){
deferred.reject({data:{},errorcode:"",errormessage:"param 'email' is mandatory in input object"})
}else{
if(typeof(data.password)=='undefined'){
deferred.reject({data:{},errorcode:"",errormessage:"param 'password' is mandatory in input object"})
}else{
var SqlString = "select id, mail, password, origin from tbl_user where mail = ?"
var param = [data.email]
self.ExecuteSingleQuery(SqlString, param).then(function(results){
if(results.length > 0)
{
if (results[0].password == data.password)
{
deferred.resolve({data:{"sessionId":results[0].id},errorcode:"",errormessage:""})
}else{
deferred.reject({data:{},errorcode:"",errormessage:"bad password"})
}
}else{
deferred.reject({data:{},errorcode:"",errormessage:"unknown user"})
}
})
}
}
return deferred.promise
},
ExecuteSingleQuery: function (queryString, parameters){
var deferred = q.defer()
var connection = connect()
connection.query(queryString, parameters, function (error, results, fields){
if(error){ deferred.reject(error)};
deferred.resolve(results)
});
return deferred.promise
},
And here's the test:
var dbconnection = require('../lib/dbConnection.js')
describe("VerifyAuthentication", function(){
it("_Returns DbResult object when user name and password match", function(){
var expectedResult = {data:{"sessionKey":"b12ac0a5-967e-40f3-8c4d-aac0f98328b2"},errorcode:"",errormessage:""}
stub = sinon.stub(dbconnection, 'ExecuteSingleQuery').returns(Promise.resolve(expectedResult))
return dbconnection.VerifyAuthentication({email:"correct#adres.com",password:"gtffr"}).then((result)=>{
expect(result.data.sessionId).to.not.be.undefined
expect(result.errorcode).to.not.be.undefined
expect(result.errormessage).to.not.be.undefined
stub.restore()
})
})
})
I always got an error 'unknown user', which is normal, because the user is indeed not in the database. However, I want to stub the 'ExecuteSingleQuery' function, avoiding it to connect to DB.
I have fixed a couple of issues in your code and posting the corrected files below.
dbConnection.js
var self = module.exports = {
VerifyAuthentication: function (data) {
var deferred = q.defer();
if (typeof (data.email) == 'undefined') {
deferred.reject({
data: {},
errorcode: '',
errormessage: "param 'email' is mandatory in input object"
});
} else {
if (typeof (data.password) == 'undefined') {
deferred.reject({
data: {},
errorcode: '',
errormessage: "param 'password' is mandatory in input object"
});
} else {
var SqlString = 'select id, mail, password, origin from tbl_user where mail = ?';
var param = [data.email];
self.ExecuteSingleQuery(SqlString, param).then(function (results) {
if (results.length > 0) {
if (results[0].password === data.password) {
deferred.resolve({
data: {
'sessionId': results[0].id
},
errorcode: '',
errormessage: ''
});
} else {
deferred.reject({
data: {},
errorcode: '',
errormessage: 'bad password'
});
}
} else {
deferred.reject({
data: {},
errorcode: '',
errormessage: 'unknown user'
});
}
});
}
}
return deferred.promise;
},
ExecuteSingleQuery: function (queryString, parameters) {
var deferred = q.defer();
var connection = connect();
connection.query(queryString, parameters, function (error, results, fields) {
if (error) {
deferred.reject(error);
}
deferred.resolve(results);
});
return deferred.promise;
}
};
dbConnection.test.js
describe('VerifyAuthentication', function () {
it('Returns DbResult object when user name and password match', function () {
var expectedResult = [{
id: '123',
password: 'gtffr'
}];
const stub = sinon.stub(dbconnection, 'ExecuteSingleQuery').resolves(expectedResult);
return dbconnection.VerifyAuthentication({
email: 'correct#adres.com',
password: 'gtffr'
}).then((result) => {
expect(result.data.sessionId).to.not.be.undefined;
expect(result.errorcode).to.not.be.undefined;
expect(result.errormessage).to.not.be.undefined;
stub.restore();
});
});
});
I am outlining the problematic parts below:
The expectedResult variable had a wrong type of value. In the
self.ExecuteSingleQuery() implementation you check for an array with length > 0. The fixed result returned by the stub, was an object instead of an array and this is why it returned the unknown user exception
The array should contain an object with { id: 'xxx', password: 'gtffr' } attributes. Password is validated against the one used by the dbconnection.VerifyAuthentication({email:"correct#adres.com",password:"gtffr"}) call
Finally, I have changed the stub statement to resolve instead of return as shown here const stub = sinon.stub(dbconnection, 'ExecuteSingleQuery').resolves(expectedResult); - this is the preferred method of resolving a promise
I have an array of objects of that type:
response.data = [{Name = "name1", Type = "text"}, {Name = "name2", Type = "text"}...]
I am trying to do add and initiate a property to all objects.
I tried:
var newObj = _.map([response.data], function (value) {
return {
value: "property : " + value.Name ,
type: "my type is : " + value.Type,
active : false
};
});
But it does not add the property
Do you know how to do this with lodash?
Because lodash map takes in input as first argument a collection. Your response.data is already a collection and you are wrapping it inside another array ([response.data]).
To fix it, avoid to wrap it:
var newObj = _.map(response.data, function (value) {
return {
value: "property : " + value.Name,
type: "my type is : " + value.Type,
active: false
};
});
Please, consider that JavaScript Array natively has map method, so you do not need lodash. You can write your piece of code in the following way:
var newObj = response.data.map(function (value) {
return {
value: "property : " + value.Name,
type: "my type is : " + value.Type,
active: false
};
});
var newObj = _.map(response.data, function (value) {
return {
value: "property : " + value.Name ,
type: "my type is : " + value.Type,
active : false
};
});