In jest I can't access to my exported module - javascript

For example, I can't access to this module, why ?
let nodeCacheClient;
module.exports = {
initNodeCache: () => {
const NodeCache = require("node-cache");
nodeCacheClient = new NodeCache();
return nodeCacheClient;
},
insertToCacheWithTtl: (key, obj, ttl) => {
return nodeCacheClient.set(key, obj, ttl);
},
getCache: (key) => {
return nodeCacheClient.get(key);
},
deleteKey: (key) => {
return nodeCacheClient.del(key);
},
};
when I run this test I get this : TypeError: Cannot read property 'get' of undefined Error
test("login a user", async () => {
try {
const response = await axiosInstance.post("users/login", {
email: "test#gmail.com",
password: "144847120",
otpCode: getCacheClient.getCache("test#gmail.com")
});
console.log(response.data);
expect(response.data.status).toBe("success");
} catch (error) {
console.log(error + " Error");
expect(error);
}
});

It’s totally normal!
Actually you got access to your module, and the error is coming into your module where the “nodeCacheClient” is undefined since it was not defined!
Your error is coming from your “getCache()” function, in this syntax:
return nodeCacheClient.get(key);
Where in your test you didnt call for the “initNodeCache()” method which will do
nodeCacheClient = new NodeCache();
So, for your test scope, the nodeCacheClient is undefined, and that’s why
nodeCacheClient.get(key);
Will return the
typeError: Cannot read property 'get' of undefined Error

Related

Error: function uses multiple asynchronous interfaces: callback and promise

Error: function uses multiple asynchronous interfaces: callback and
promise
to use the callback interface: do not return a promise
to use the promise interface: remove the last argument to the function
I'm trying to write a cucumber test to one of my GET node API, and keep getting the above, looked at few GitHub and stack-overflow posts, and could not understand the issue, below are my test method details.
App.ts
async getSsoId(refId: any): Promise<string> {
let ssoId = '';
const secrets = await this.vaultService.getClientSecrets();
this.decrypt(refId, secrets.encryption_secret, secrets.encryption_Id).then((value: any) => {
ssoId = value;
});
return ssoId;
}
api.get('/status', async (req, res) => {
let id;
const statusCode = 200;
try {
id = await this.getId(String('123456'));
} catch (err: any) {
throw new ApiError('Error fetching id');
}
try {
const item = await dbService.getItem(id);
if (item) {
statusCode = 201;
} else {
statusCode = 202;
}
} catch (err: any) {
throw new ApiError(
'The API encountered an error while attempting to communicate with the DB service.'
);
}
res.status(statusCode).send(statusCode);
});
Step Definition:
Given('a valid customer', function () {});
When("I call the get-id api", { timeout: 2 * 5000 }, async function (val) {
util.callGetIdAPI().then((response) => {
this.setApiResponseStatus(response.status);
this.setResponseBody(JSON.stringify(response.body));
});
});
Then("the apiResponseStatus should be <apiResponseStatus>", function (status) {
assert.strictEqual(status, this.apiResponseStatus);
});
Then("the responseBody should be {string}", function (responseBody) {
assert.equal(responseBody, this.responseBody);
});
Util Function
callGetIdAPI = async () => {
const headers = {
'Content-Type': 'application/json;v=1',
Accept: 'application/json;v=1'
}
const client = await getClient('url');
const options = {
method: 'GET',
headers: headers,
version: 3
};
let response;
try {
response = await client.get('/status', options);
return {
status: response.statusCode,
body: response.body
};
} catch(error) {
return {
status: error.statusCode,
body: {
error: {
id: error.id,
message: error.message
}
}
}
}
};
I'm new to this and trying to understand how multiple Premisses and Callbacks works in parallel, any thoughts or inputs on what possibly cause the error, or am I missing anything ??

Error in NuxtJS: Cannot Convert Undefined or Null to Object

I am getting the following error (it won't even get to the console.log part of my code):
ERROR error in cloudinary module Cannot convert undefined or null to object 09:05:40
at Function.keys (<anonymous>)
at setSignature (modules\cloudinary\index.js:15:14)
Here is my code:
modules/cloudinary/index.js:
export default function () {
this.nuxt.hook('render:setupMiddleware', (app) => {
app.use('/api/cloudinary/signature', setSignature)
})
function setSignature(req, res) {
try {
const payload = []
Object.keys(req.body).forEach((key) => {
payload.push(`${key}=${req.body[key]}`)
})
console.log(payload)
} catch (error) {
console.error('error in cloudinary module', error)
}
}
}
Something going on with the Object here. Anyone spot anything?
Updated:
Doing the following console.log gives me undefined on the req.body:
export default function () {
// const config = this.options.privateRuntimeConfig.cloudinary
this.nuxt.hook('render:setupMiddleware', (app) => {
app.use('/api/cloudinary/signature', setSignature)
})
function setSignature(req, res) {
try {
console.log(req.body)

React Native AsyncStorage=> TypeError: Cannot read property 'login' of undefined

This error occur while calling login function:
TypeError: Cannot read property 'login' of undefined
How to solve that problem error calling login() function.
I called login() in AsyncStorage multiSet callback function. when I try to access the other property by using this keyword or without any keywords it occurs property not found.
facebookLogin() {
LoginManager.logInWithPermissions(["public_profile","email","user_birthday","user_friends"]).then(
function(result) {
if (result.isCancelled) {
console.log("Login cancelled");
} else {
console.log(
"Login success with permissions: " +
result.grantedPermissions.toString()
);
AccessToken.getCurrentAccessToken().then(
(data) => {
console.log(data.accessToken.toString());
fetch('https://graph.facebook.com/v2.5/me?fields=email,name,friends,birthday&access_token=' + data.accessToken)
.then((response) => response.json())
.then((json) => {
AsyncStorage.multiSet([
['name', json.name.toString()],
['email', json.email.toString()],
['photo', 'http://graph.facebook.com/'+json.id+'/picture?type=square']],
() => {
console.log("FACEBOOK Login Successeded..");
this.login();
});
})
.catch(() => {
console.log('ERROR GETTING DATA FROM FACEBOOK')
});
}
);
}
},
function(error) {
console.log("Login fail with error: " + error);
}
);
}
login = () => {
this.props.navigation.replace("Dashboard");
}
Just replace your facebookLogin() { ... }. with facebookLogin = () => { ... }
With this fat arrow function. Hope this helps . feel free for doubts
Replace this code "this.login()" with "this.login"

Conditionally execute branch if variable is not undefined

I have a piece of code and a variable sometimes comes as undefined but I need to validate if that value is undefined to pass the execution of code
the validation I provided is not solving the problem
_getKeycodeScans = (data) => this.props.getKeycodeScans(data.keycode.uid, 1).then(() => {
this.setState({detailsModalVisible: true, homeDetails: data});
}).catch(error => {
debugger
const { serverError } = JSON.parse(error.message);
this.setState({ serverError, loading: false });
});
_openDetailsModal = (data) => () => Promise.all([
console.log('&&&&&&&&&&&&&&&&&&&&**********&&&&&&&&&&&&&&&&&&&&&'),
console.log(data),
this._getKeycodeScans(data),
this._getKeycodeImageDataUrl(data),
this._getHomes(data)
]);
When the _openDetailsModal gets hit and it calls the functions inside and the uid is undefined.
I get the error message: TypeError: Cannot read property 'uid' of undefined.
When uid is undefined I actually don't need the data
If your goal is to only continue executing your script if data.keycode.uid is not undefined, you could just:
_getKeycodeScans = (data) => {
if(!data.keycode || data.keycode.uid === undefined) {
return;
}
return this.props.getKeycodeScans(data.keycode.uid, 1).then(() => {
this.setState({detailsModalVisible: true, homeDetails: data});
}).catch(error => {
const { serverError } = JSON.parse(error.message);
this.setState({ serverError, loading: false });
});
}

How to handle callback function in javascript?

The async function itself should make use of the lookup() function what I have used inside the async function,but return the result inside the callback.
The parameters for the callback are err and res.
If an Error has been thrown by lookup() then it should be passed to
err, otherwise err is null or undefined.If a result has been returned by lookup() then it should be passed to res, otherwise res is null or undefined,I have other two tests for checking property as like user but I have shortened the code as much as possible. the problem is callback inside lookupAsync() function.
const users = [
{
"login": "norvig",
"firstName": "Peter",
"lastName": "Norvig",
"likes": ["AI", "Search", "NASA", "Mars"]
}
];
// lookupAsync()
const lookupAsync = (login, prop, callback) => {
// Only change code below this line
const found = users.find(function(e) {
return e.login === login;
});
if (!found) {
throw "Could not find user.";
} else {
if (prop in found) {
return found[prop];
} else {
throw "Could not find property";
}
}
//my current concept according to suggestion but trying to set in the
code.
function mycallback(callback) {
var err,res;
callback(err,res);
}
mycallback( function() {
console.log();
});
};
test('lookupAsync() likes', assert => {
const msg = `lookupAsync(<login>, 'likes', callback) should return
likes for the specified user.`;
lookupAsync('norvig', 'likes', function(err, res){
const actual = res;
const expected = ["AI", "Search", "NASA", "Mars"];
assert.deepEqual(actual, expected, msg);
assert.end();
});
});
test('lookupAsync() with unknown user', assert => {
const msg = `lookupAsync() with unknown user should return an error
with the correct message.`;
const value = lookupAsync('nobody', 'likes', function(err, res){
const actual = err.message;
const expected = 'Could not find user.';
assert.equal(actual, expected, msg);
assert.end();
});
});
Let me do it for you
const lookupAsync = (login, prop, callback) => {
const found = users.find(function(e) {
return e.login === login;
});
if (!found) {
callback(new Error("Could not find user."));
} else {
if (prop in found) {
callback(null, found[prop]);
} else {
callback(new Error("Could not find property"));
}
}
}

Categories