sinon stub is not working - testing

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

Related

Store Auth::user()-id in DB using SQL query in laravel

I want to store Auth::user()->id on the default column user_id in the SQL query shown below.
I tried to set put like this but does not send any data to the database.
public function saveLoadingsData() {
//Validate for a valid Post Request
if (isset($_POST['orderNumber']) && isset($_POST['Truck']) && isset($_POST['receiptNumber']) && isset($_POST['items'])) {
// {"orderNumber":"CRS1104200001","agentId":"3","items":[{"itemId":"4","itemName":"Embe","quantity":"13"}]}
$orderNumber = $_POST['orderNumber'];
$items = $_POST['items'];
$receiptNumber = $_POST['receiptNumber'];
$Truck = $_POST['Truck'];
$driverName = $_POST['driverName'];
foreach ($items as $singleItem) {
$data = array('order_no' => $orderNumber,'user_id'=>Auth::user()->id,"receiptNumber" => $receiptNumber, "Truck" => $Truck, "driverName" => $driverName, "pid" => $singleItem['itemId'], "qty" => $singleItem['quantity']);
// print_r($data);
DB::table('loadings')->insert($data);
// return redirect()->back();
}
// return redirect()->back();
echo "Success";
}
My ajax function
$("#btnSaveOrder").on('click', function(e){
var orderNumber=$("#order_no").val();
var receiptNumber=$("#receiptNumber").val();
var Truck=$("#Truck").val();
var driverName=$("#driverName").val();
var jsonData=convertTableToJson();
$.ajax('/api/loading/saveLoadingsData', {
type: 'POST',
data: {
orderNumber:orderNumber,
receiptNumber:receiptNumber,
Truck:Truck,
driverName:driverName,
items:jsonData
},
success: function (data, status, xhr) {
alert("Data Saved");
document.location.reload(true);
},
error: function (jqXhr, textStatus, errorMessage) {
console.log(errorMessage);
}
});
});
var convertTableToJson = function(){
var rows = [];
$('table#tableSelectedItems tr').each(function(i, n){
if (i!=0) {
var $row = $(n);
rows.push({
itemId: $row.find('td:eq(0)').text(),
itemName: $row.find('td:eq(1)').text(),
quantity: $row.find('td:eq(2)').text(),
});
}
});
return rows;
};
My api route
Route::post('loading/saveLoadingsData', 'LoadingController#saveLoadingsData');
Can someone help me?
I recommend you the following
Pass the $request object in your method and log all object, maybe are missing data and for that reason it does not meet the condition:
saveLoadingsData(Request $request){
Log::info(json_encode($request->all()));`
}
Then check your logs files to see the result in /storage/logs/laravel.log

Rewriting the Dataprovider for multiple api requests broke it and now returns the error "Cannot read property 'hasOwnProperty' of undefined"

I am using the react-admin package and it has come to my attention that I needed to rewrite my functioning data provider to merge two different api request results into one array of data before passing the data to the resource component that would display it. After my rewrite I console log the data being returned and it is correct, but no matter what I have tried I always get the "Cannot read property 'hasOwnProperty' of undefined" error before my console.log of the data, and then I get the same error message a few seconds later, and nothing gets displayed.
in dataprovider.js (displays the data in the resource component)
export default (type, resource, params) => {
var apiUrl = `https://request1url.com/api`;
let query = '';
let url = '';
const options = {
headers : new Headers({
Accept: 'application/json',
}),
};
switch (type) {
case GET_LIST: {
if(resource === 'errors'){
query = '/query/errors';
}
if(resource === 'people'){
query = '/query/users';
}
url = `${apiUrl}${query}`;
break;
}
default:
throw new Error(`Unsupported Data Provider request type ${type}`);
}
return fetch(url, options)
.then(res => {
return res.json()
})
.then(json => {
var data = [];
var result = json.data.result;
for(var i = 0; i < result.length; i++){
result[i].id = i
data.push(result[i])
}
}
console.log(data)
switch (type) {
case GET_LIST:
return {
data: data,
total: data.length
}
case GET_ONE:
return {
data: data,
}
default:
return { data: data};
}
});
};
in NEWdataprovider.js (rewrite)
export default (type, resource, params) => {
const apiRequests = ['https://request1url.com/api','https://request2url.com/api'];
let query = '';
const options = {
headers : new Headers({
Accept: 'application/json',
}),
};
switch (type) {
case GET_LIST: {
if(resource === 'errors'){
query = '/query/errors';
}
if(resource === 'people'){
query = '/query/users';
}
break;
}
default:
throw new Error(`Unsupported Data Provider request type ${type}`);
}
var req1 = fetch(`${apiRequests[0]}${query}`, options).then(function(response){
return response.json()
});
var req2 = fetch(`${apiRequests[1]}${query}`, options).then(function(response){
return response.json()
});
Promise.all([req1,req2]).then(function(values){
var data = [];
var result1 = values[0].data.result;
var result2 = values[1].data.result;
for(var i = 0; i < result1.length; i++){
result1[i].id = i
data.push(result1[i])
}
for(var j = 0; j < result2.length; j++){
result2[j].id = j
data.push(result2[j])
}
console.log(data)
switch (type) {
case GET_LIST:
return {
data: data,
total: data.length
}
default:
return { data: data};
}
});
};
in App.js
<Admin dataProvider={dataProvider}>
<Resource name="errors" list={errors} />
<Resource name="people" list={people} />
</Admin>
);
in the console.log the data logged is the correct format, and data to be displayed, but with the original dataprovider it displayed the list of items, and the new dataprovider returns the error message "Cannot read property 'hasOwnProperty' of undefined"
Your dataprovider needs to return a promise.
Per the docs...
/**
* Query a data provider and return a promise for a response
*
* #example
* dataProvider(GET_ONE, 'posts', { id: 123 })
* => Promise.resolve({ data: { id: 123, title: "hello, world" } })
*
* #param {string} type Request type, e.g GET_LIST
* #param {string} resource Resource name, e.g. "posts"
* #param {Object} payload Request parameters. Depends on the action type
* #returns {Promise} the Promise for a response
*/
const dataProvider = (type, resource, params) => new Promise();
Try return Promise.all() instead.
export default (type, resource, params) => {
const apiRequests = ['https://request1url.com/api','https://request2url.com/api'];
let query = '';
const options = {
headers : new Headers({
Accept: 'application/json',
}),
};
switch (type) {
case GET_LIST: {
if(resource === 'errors'){
query = '/query/errors';
}
if(resource === 'people'){
query = '/query/users';
}
break;
}
default:
throw new Error(`Unsupported Data Provider request type ${type}`);
}
var req1 = fetch(`${apiRequests[0]}${query}`, options).then(function(response){
return response.json()
});
var req2 = fetch(`${apiRequests[1]}${query}`, options).then(function(response){
return response.json()
});
return Promise.all([req1,req2]).then(function(values){
var data = [];
var result1 = values[0].data.result;
var result2 = values[1].data.result;
for(var i = 0; i < result1.length; i++){
result1[i].id = i
data.push(result1[i])
}
for(var j = 0; j < result2.length; j++){
result2[j].id = j
data.push(result2[j])
}
console.log(data)
switch (type) {
case GET_LIST:
return {
data: data,
total: data.length
}
default:
return { data: data};
}
});
};

I am getting this error ,"value for message cannot be cast from double to string"

I am getting this error when I am trying pass object to axios method "value for message cannot be cast from double to string". Does any one have Idea about this.
I have added my two functions.
addNotes = (formData) => {
let noteText = ''
Object.keys(formData).map((item) => {
noteText += formData[item] !== undefined ? `${formData[item]} \n` : ``
})
let localLocation = `${this.state.localAddress.locality}, ${this.state.localAddress.subLocality}`
let { userMetaData, graphListlimit, graphListoffset, imdCode } = this.state
let obj = {
'edEmployeeCode': userMetaData.ed_employee_code,
'edName': userMetaData.ed_name,
'edRoleCode': userMetaData.ed_role_code,
'imdCode': imdCode,
'imdSegment': null,
'bnNoteText': noteText,
'location': localLocation,
'meetingType': this.state.meetingType
}
this.props.onAddNotesAction(obj)
}
export const addNotesAction = (obj) => {
let params = {
ed_employee_code: obj.empCode,
ed_role_code: obj.empRoleCode,
ed_channel: obj.empChannel,
ed_name: obj.edName,
imd_code: obj.imdCode,
imd_segment: null,
bn_note_text: obj.bnNoteText,
location: obj.location,
meeting_type: obj.meetingType
}
return dispatch => {
axios.defaults.headers.common['Authorization'] = obj.token;
axios.post(`${Config.apiRootPath}/meetings/addbranchnote`,
params,
).then(response => {
dispatch(addNotesSuccess(response));
}).catch(err => {
dispatch(addNotesFailure(err.response));
});
};
};

Running a stored procedure with NodeJS and MSSQL package error

Im trying to get the MSSQL nodejs package to return the results of a stored procedure from Microsoft SQL server using the code below. However the error I get is...
[TypeError: Cannot read property 'type' of undefined]
I'm not sure I have done the inputs correctly as I couldn't find an example with more than one input anywhere online.
Any ideas?
exports.executeSqlStoredProd = function (callback) {
var conn = new sqlDb.Connection(settings.dbConfig)
conn.connect().then(function () {
var req = new sqlDb.Request(conn);
req.input('ProductEntryID', req.Int, 3299);
req.input('LoginEntryID', req.Int, 4);
req.input('TempLoginEntryId', req.Int, -1);
req.input('AddToWishList', req.Bit, 0);
req.input('WebPortalId', req.Int, 0);
req.execute('J_ViewAProduct').then(function(err, recordsets) {
console.log(recordsets);
callback(recordsets)
})}).catch(function(err){
console.log(err);
callback(null, err);
});
}
I did the request sucessfully using the package "Seriate" but would prefer to use mssql. The code that worked for "Seriate" is below.
exports.getVAP = function(req, resp, pid) {
sql.execute({
procedure: "J_ViewAProduct",
params: {
ProductEntryID: {
type: sql.INT,
val: pid
},
LoginEntryID: {
type: sql.Int,
val: 4
},
TempLoginEntryId: {
type: sql.Int,
val: -1
},
AddToWishList: {
type: sql.Bit,
val: 0
},
WebPortalId: {
type: sql.Int,
val: 0
}
}
}).then(function(results){
console.log(results)
httpMsgs.sendJSON(req, resp, results)
//httpMsgs.sendJSON(req, resp, results[0])
resp.end();
}), function(err){
httpMsgs.show500(req, resp, err)
}
};
I think the line's
req.input('ProductEntryID', req.Int, 3299);
req.input('LoginEntryID', req.Int, 4);
req.input('TempLoginEntryId', req.Int, -1);
req.input('AddToWishList', req.Bit, 0);
req.input('WebPortalId', req.Int, 0);
which has req.input thats wrong it seems.
Please try this code
var sql = require('mssql');
var config = {
user: 'sa',
password: '---',
server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
database: 'Test'
}
var getCities = function() {
var conn = new sql.Connection(config);
conn.connect().then(function(conn) {
var request = new sql.Request(conn);
request.input('City', sql.VarChar(30), 'Cbe');
request.input('NameNew', sql.VarChar(30), 'Cbe');
request.execute('spTest').then(function(err, recordsets, returnValue, affected) {
console.dir(recordsets);
console.dir(err);
}).catch(function(err) {
console.log(err);
});
});
}
getCities();
I tried this myself and its giving the results.
I don't know if this would be helpful or not but this is how I did
let executeQuery = async (value, country) => {
try {
let pool = await sql.connect(dbConfig);
let results = await pool.request()
.input('input_parameter', sql.Int, value)
.input('Country', sql.VarChar(50), country)
// .output('output_parameter', sql.VarChar(50))
.execute('procedure_name')
console.dir(results);
} catch (err) {
res.json({
"error": true,
"message": "Error executing query"
})
}
}
executeQuery(value, country);
I've used async and await method to make it more readable.

dojo ItemFileReadStore.getValue mixed return value is not handled as string

I'am using dojo.data.ItemFileReadStore to query a json file with data. the main purpose is finding translations at Js level.
The Json data has "id" the word and "t" the translation
function translate(word)
{
var json = '/my/language/path/es.json';
var reader = new dojo.data.ItemFileReadStore({
url: json
});
var queryObj = {};
queryObj["id"] = word;
reader.fetch({
query: queryObj,
onComplete: function(items, request){
if (items.length > 0) {
var t = reader.getValue(items[0], 't');
if (dojo.isString(t)) {
return t;
}
}
return word;
},
onError: function(error, request){
return word;
}
});
}
The return value is always a undefined wether there is a translation or not. any ideas?
I tried typecasting with no success.
You can do it like this:
function translate(wordId) {
var translatedWord= wordId;
var store = new dojo.data.ItemFileReadStore({ data: storeData });
store.fetch({ query: { id: wordId },
onItem: function (item) {
translatedWord= (store.getValue(item, 't'));
}
});
return translatedWord;
}