How to write test cases in Jest for login page - javascript

The following code is what I have written in order for the Admin to log in to the system. I am now trying to carry out unit testing and have to test the ValidateLogin for admin in particular. I have chosen jest to do that.
I created a test file:
const LoginController = reqire('./LoginController')
test('login to the system', () => {
expect(true).toBe(true);
})
Instead of checking for true to be true. I want to check for the username and password to be true. Please explain how should I do it.
Following is the code for login:
class User {
username;
password;
email;
firstName;
lastName;
roleName;
constructor(username,password,email,firstName, lastName, roleName){
this.username = username;
this.password = password;
this.email = email;
this.firstName = firstName;
this.lastName = lastName;
this.roleName = roleName;
}
getlogininfo(username, password, callback) {
var sql = "SELECT * FROM User Where username = '" + username +
"' AND password = '" + password + "'";
var Username;
var dataRes;
con.query(sql, function(err, results){
if (err){
throw err;
}
if(results.length>0) { //result is not empty
Username = results[0].username; // Scope is larger than function
dataRes = {
username: results[0].username,
firstName: results[0].firstName,
lastName: results[0].lastName,
roleName: results[0].roleName
}
return callback(dataRes);
} else {
return callback(false);
}
})
}
}
exports.User = User
class LoginController {
ValidateLogin(req, res) {
let user = new User();
var dataRes;
var username = req.body.username
var password = req.body.password
console.log(username + "kekw" + password);
user.getlogininfo(username, password, function(result){
if(result) {
dataRes = result;
var session;
// Login endpoint
if(dataRes.roleName == "useradmin") {
console.log("Call User Admin Dashboard");
res.redirect("/UserAdmin");
}
else if(dataRes.roleName == "manager") {
console.log("Call Manager Dashboard");
res.redirect("/Manager");
}
else if(dataRes.roleName == "staff") {
console.log("Called Staff Dashboard");
res.redirect('/Staff');
}
else if(dataRes.roleName == "customer") {
console.log("Called Customer Dashboard");
res.redirect('/Customer');
}
/*
else if(dataRes.role == "Pharmacist") {
console.log("Called Pharmacist home");
res.redirect('/PharmacistHome');
}
else if(dataRes.role == "Patient") {
console.log("Called Patient home");
res.redirect('/PatientHome');
}*/
}
else {
req.flash('message', 'Wrong Username or Password!')
res.redirect("/?error=true");
return false;
}
});
}
}
//module.exports = LoginController;
exports.LoginController = LoginController;
I want to write test cases for username and password for the useradmin login. How do I do so? Thanks.

Could you please send your complete error code? It would be very helpful to get a solution. Although i think it could be an error with ES6 modules. Check if you have "type": "module" in your package.json. If that's the case you have to import your LoginController with import * from './LoginController'
You wrote „require“ wrong:
Like this: const LoginController = reqire('./LoginController');

Related

Express: Variable not getting rewritten

I have this JS code that I've been looking at for the past 2 hours and cannot find the reason why the variable "message" doesn't get rewritten to "User already exists.". The thing is that "Inside first if" runs, but the variable message doesn't get rewritten to "User already exists."
async function postRegister(req, res) {
const familyName = req.body.familyName;
const email = req.body.email;
const password = req.body.password;
const repeatPassword = req.body.repeatPassword;
let message = 'msg';
// Check if user already exists
await db
.promise()
.query(
'SELECT * FROM users WHERE email = ?',
[email],
function (err, results) {
if (results.length > 1) {
console.log('Inside first if');
message = 'User already exists.';
return;
} else {
if (password !== repeatPassword) {
console.log('passwords do not match');
} else {
const newUser = new User(familyName, password, email);
newUser.save();
res.redirect('/login');
}
}
}
);
console.log(message);
res.render('authentication/register', { message: message });
}
Try this. Do not find all the users. Find only one since there will not be any duplicate entry.
try {
const user = await User.findOne({ email: email})
let message = ''
if(user) {
message = 'User already exists'
// better return the response here
}
if (password !== repeatPassword) {
message 'passwords do not match'
}
if(message) {
// Some error message is present, perform your action here
}
// Create your user
res.redirect('/login')
} catch(err) {
console.log(err)
}

firebase login authentication gives me that email must be a valid string

It always gives me "first argument (email) must be a valid string" and it doesn't login
i don't know if the problem is in the js code but im pretty sure it's not in the html .
and another question .. do i need the " onAuthStateChanged " function?
<script>
var rightAccount = 0;
var email = $("#inputEmail").val();
var password = $("#inputPassword").val();
SignIn();
function SignIn(email,password) {
firebase.auth().signInWithEmailAndPassword(email, password)
.then((user) => {
authStateListener();
rightAccount = 1;
//Signed in
// ...
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorMessage);
alert(errorMessage);
});
};
function authStateListener() {
// [START auth_state_listener]
firebase.auth().onAuthStateChanged((user) => {
if (user) {
var uid = user.uid;
currentUser = user;
console.log(currentUser.email + " has logged in")
} else {
// ...
}
});
// [END auth_state_listener]
};
if (rightAccount == 1) {
setTimeout(function Redirect() {
window.location.replace("Website/homePage.php");
}, 2000)
}
</script>
You must pass email and password values to function. Otherwise it will be give error.
...
var email = $("#inputEmail").val();
var password = $("#inputPassword").val();
SignIn(email, password); // <-- Here pass them
...

How to avoid observable delay in angular or make sure my function gets called only when observable is ready

I have a login function which calls Firebase SDK method to authenticate with email. This Firebase method returns non-null Promise of UserCredential, so it says in Firebase docs. So I use .then() to wait until user is logged in, authenticated and then console.log his info and redirect to home. Unfortunately it doesn't work. I get undefined from console.log(value.email); in the console, not working from
if (this.userDetails) {
console.log("hello im user" + " " + email);
} else {
console.log("not working");
}
and errorTypeError: Cannot read property 'router' of undefined from:
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log("error" + error);
});
then immediately after one or two seconds, it finally starts working, prints out hello im user lajmis#mail.com from
constructor(private _firebaseAuth: AngularFireAuth, private router: Router) {
this.user = _firebaseAuth.authState;
this.loggedIn = !!sessionStorage.getItem('user');
this.user.subscribe(
(user) => {
if (user && user.uid) {
this.userDetails = user;
var email = this.userDetails.email;
console.log("hello im user" + " " + email);
this.setCurrentUser(email);
this.loggedIn = true;
console.log(this.userDetails);
} else {
this.userDetails = null;
}
}
);
}
and this.userDetails.
Why is this happening? Here is the full code:
export class AuthService {
private user: Observable<firebase.User>;
private userDetails: firebase.User = null;
public loggedIn = false;
constructor(private _firebaseAuth: AngularFireAuth, private router: Router) {
this.user = _firebaseAuth.authState;
this.loggedIn = !!sessionStorage.getItem('user');
this.user.subscribe(
(user) => {
if (user && user.uid) {
this.userDetails = user;
var email = this.userDetails.email;
console.log("hello im user" + " " + email);
this.setCurrentUser(email);
this.loggedIn = true;
console.log(this.userDetails);
} else {
this.userDetails = null;
}
}
);
}
// Set current user in your session after a successful login
setCurrentUser(email: string): void {
sessionStorage.setItem('user', email);
this.loggedIn = true;
}
// Get currently logged in user from session
getCurrentUser(): string | any {
return sessionStorage.getItem('user') || undefined;
}
isLoggedIn() {
return this.loggedIn;
}
logUserIn(email, pass) {
firebase.auth().signInWithEmailAndPassword(email, pass).then(function(value) {
console.log(value.email);
this.router.navigate(['']);
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log("error" + error);
});
if (this.userDetails) {
console.log("hello im user" + " " + email);
} else {
console.log("not working");
}
}
logUserIn is non blocking - so the workflow will be;
call constructor
call this.user.subscribe
call logUserIn
call firebase.auth().signInWithEmailAndPassword
call if (this.userDetails)
receive response from firebase.auth().signInWithEmailAndPassword
call .then(function(value) {
call this.router.navigate(['']);
receive response from this.user.subscribe
Therefore the console.log will output not working and a few seconds later the this.user.subscribe receives the user object.
router cannot be accessed because you're not using an arrow function. Use an arrow function to maintain access to this.
Perhaps try a workflow such as the following;
constructor(private _firebaseAuth: AngularFireAuth, private router: Router) {
this.user = _firebaseAuth.authState;
this.loggedIn = !!sessionStorage.getItem('user');
this.user
.subscribe(user => {
console.log('constructor user: ' + user);
this.updateUser(user);
});
}
updateUser(user) {
if (user && user.id) {
this.userDetails = user;
var email = this.userDetails.email;
console.log("hello im user" + " " + email);
this.setCurrentUser(email);
this.loggedIn = true;
console.log(this.userDetails);
} else {
this.userDetails = null;
}
}
logUserIn(email, pass) {
firebase.auth().signInWithEmailAndPassword(email, pass)
.then(user => {
console.log('logUserIn: ' + user);
this.updateUser(user);
this.router.navigate(['']);
})
.catch(error => {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log("error" + error);
});
}
This way both the logUserIn and constructor can update the userDetails when they receive the user object from Firebase.
It will also avoid you redirecting before this.userDetails have been set.

How to check if there's no errors in authentication process in Firebase Web?

I'm new to Web Development, especially to Firebase.
I'm trying to check if there are no errors while creating a user in Firebase Authentication system, so I can put this user into Database.
Here's my code:
function register() {
var firebaseRef = firebase.database().ref();
var shaObj = new jsSHA("SHA-256", "TEXT")
shaObj.update(passwordField.value)
//console.log(hash)
var email = emailField.value
var password = shaObj.getHash("HEX")
if (isBarber != null) {
if (email != "" && password != "") {
firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
$('#errorMsg').show();
$('#errorMsg').text(error.message);
if (error === null) {
var user = firebase.auth().currentUser;
var userID = user.uid;
firebase.database().ref('users/' + userID).set({
userEmail: email,
userPassword: password,
userIsBarber: isBarber
})
}
});
} else {
alert('Email or password fields are empty')
}
} else {
alert('Select your role')
}
}
createUserWithEmailAndPassword works properly and creates a user, but I don't know how to check if there are no errors so I could add this user to database.
Thanks a lot
You can use then() to action on a successful registration as follows:
firebase.auth().createUserWithEmailAndPassword(email, password).then(function(user) {
//Registration is successful
var user = firebase.auth().currentUser;
var userID = user.uid;
firebase.database().ref('users/' + userID).set({
userEmail: email,
userPassword: password,
userIsBarber: isBarber
})
}).catch(error) {
//Registration unsuccessful
$('#errorMsg').show();
$('#errorMsg').text(error.message);
});

Alloy MVC Framework Titanium Network (Model)

I'm trying to authenticate using the Model in Alloy. I have been trying to figure this problem out since yesterday. If anybody could help me, I'd really appreciate it.
So, I have a view login.xml, then a controller login.js. The login.js contains the following function:
var user = Alloy.Models.user; //my user.js model
function login(e) {
if($.username.value !== '' && $.password.value !== ''){
if(user.login($.username.value, $.password.value)){
Alloy.createController('home').getView().open();
$.login.close();
}
}else{
alert('Username and/or Password required!');
}
}
Then in my user.js model, it's like this:
extendModel : function(Model) {
_.extend(Model.prototype, {
login: function(username, password) {
var first_name, last_name, email;
var _this = this;
var url = 'http://myurl.com/test.php';
var auth = Ti.Network.createHTTPClient({
onerror: function(e){
alert(e.error);
},
onload: function(){
var json = this.responseText;
var response = JSON.parse(json);
if(response.logged == true){
first_name = response.f_name;
last_name = response.l_name;
email = response.email;
_this.set({
loggedIn: 1,
username: email,
realname: first_name + ' ' + last_name,
email: email,
});
_this.save();
}else{
alert(response.message);
}
},
});
auth.open('POST', url);
var params = {
usernames: username,
passwords: password,
};
auth.send(params);
alert(_this.get('email')); //alert email
},
});
When I click on login in login.xml it calls the function login in index.js. So, now my problem is that, when I click the button for the first time, I get an empty alert from alert(_this.get('email')), but then when I click the button the second time, everything works fine, it alerts the email. I have no idea what's going on. Thank you for the help.
I think I figured it out, for people that might stumble upon the same problem. I used callback function to do it.
Refer to this Titanium HTTP Request
Now my user.js looks like this:
extendModel : function(Model) {
_.extend(Model.prototype, {
login: function(username, password, callback) {
var first_name, last_name, email;
var _this = this;
var url = 'http://myurl.com/test.php';
var auth = Ti.Network.createHTTPClient({
onerror: function(e){
alert(e.error);
},
onload: function(){
var json = this.responseText;
var response = JSON.parse(json);
if(response.logged == true){
first_name = response.f_name;
last_name = response.l_name;
email = response.email;
_this.set({
loggedIn: 1,
username: email,
realname: first_name + ' ' + last_name,
email: email,
});
_this.save();
callback(foo); //whatever you want to send
}else{
alert(response.message);
}
},
});
auth.open('POST', url);
var params = {
usernames: username,
passwords: password,
};
auth.send(params);
},
});
And my login.js looks like this:
var user = Alloy.Models.user; //my user.js model
function login(e) {
if($.username.value !== '' && $.password.value !== ''){
var logged_in = user.login($.username.value, $.password.value, function(foo){
if(foo == bar)
call_another_function();
});
}else{
alert('Username and/or Password required!');
}
}
Thanks. I hope this helps.

Categories

Resources