Commit 10e7e354 authored by Irina Kera Gundersen's avatar Irina Kera Gundersen
Browse files

Refactor code in frontend

parent e2684002
Pipeline #128209 passed with stages
in 2 minutes and 45 seconds
module.exports = {
"env": {
"browser": true,
"es2021": true
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaVersion": 12,
"sourceType": "module"
},
"rules": {
}
};
{
"eslint.alwaysShowStatus": true,
"eslint.run": "onSave"
}
\ No newline at end of file
......@@ -4,14 +4,15 @@ let deleteButton;
let editButton;
let oldFormData;
function handleCancelButtonDuringEdit() {
function disableExerciseForm() {
setReadOnly(true, "#form-exercise");
okButton.className += " hide";
deleteButton.className += " hide";
cancelButton.className += " hide";
editButton.className = editButton.className.replace(" hide", "");
}
function handleCancelButtonDuringEdit() {
disableExerciseForm();
cancelButton.removeEventListener("click", handleCancelButtonDuringEdit);
let form = document.querySelector("#form-exercise");
......@@ -34,10 +35,12 @@ function handleCancelButtonDuringCreate() {
async function createExercise() {
let form = document.querySelector("#form-exercise");
let formData = new FormData(form);
let body = {"name": formData.get("name"),
let body = {
"name": formData.get("name"),
"description": formData.get("description"),
"category": formData.get("category"),
"unit": formData.get("unit")};
"unit": formData.get("unit")
};
let response = await sendRequest("POST", `${HOST}/api/exercises/`, body);
......@@ -103,10 +106,12 @@ async function retrieveExercise(id) {
async function updateExercise(id) {
let form = document.querySelector("#form-exercise");
let formData = new FormData(form);
let body = {"name": formData.get("name"),
let body = {
"name": formData.get("name"),
"description": formData.get("description"),
"category": formData.get("category"),
"unit": formData.get("unit")};
"unit": formData.get("unit")
};
let response = await sendRequest("PUT", `${HOST}/api/exercises/${id}/`, body);
if (!response.ok) {
......@@ -114,13 +119,7 @@ async function updateExercise(id) {
let alert = createAlert(`Could not update exercise ${id}`, data);
document.body.prepend(alert);
} else {
// duplicate code from handleCancelButtonDuringEdit
// you should refactor this
setReadOnly(true, "#form-exercise");
okButton.className += " hide";
deleteButton.className += " hide";
cancelButton.className += " hide";
editButton.className = editButton.className.replace(" hide", "");
disableExerciseForm();
cancelButton.removeEventListener("click", handleCancelButtonDuringEdit);
......
async function login() {
let form = document.querySelector("#form-login");
let formData = new FormData(form);
let body = {"username": formData.get("username"), "password": formData.get("password")};
let body = { "username": formData.get("username"), "password": formData.get("password") };
let response = await sendRequest("POST", `${HOST}/api/token/`, body)
if (response.ok) {
......@@ -19,15 +19,15 @@ async function login() {
}
// Sets cookie if remember me checked
var rememberMe = document.getElementById("rememberMe").checked;
let rememberMe = document.getElementById("rememberMe").checked;
if (rememberMe) {
let response = await sendRequest("GET", `${HOST}/api/remember_me/`);
if(response.ok) {
if (response.ok) {
let data = await response.json();
setCookie("remember_me", data.remember_me, 3000000000, "/");
}
}
};
}
// Used for login if remember me cookie exists
async function rememberMe() {
......@@ -44,10 +44,10 @@ async function rememberMe() {
let alert = createAlert("Login failed!", data);
document.body.prepend(alert);
}
};
}
window.onload = function() {
if (getCookieValue('remember_me')){
window.onload = function () {
if (getCookieValue('remember_me')) {
rememberMe();
}
};
......
......@@ -9,8 +9,6 @@ function isUserAuthenticated() {
}
function updateNavBar() {
let nav = document.querySelector("nav");
// Emphasize link to current page
if (
window.location.pathname == "/" ||
......
......@@ -6,32 +6,29 @@ async function fetchWorkouts(ordering) {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
} else {
}
let data = await response.json();
let workouts = data.results;
return workouts;
}
}
function isLastWeek(date) {
let lastWeek = new Date();
let today = new Date();
let past = lastWeek.getDate() - 7;
const today = new Date();
const past = lastWeek.getDate() - 7;
lastWeek.setDate(past);
console.log(today);
return date >= lastWeek && date <= today;
}
function isLastMonth(date) {
let lastMonth = new Date();
let today = new Date();
let past = lastMonth.getDate() - 30;
const today = new Date();
const past = lastMonth.getDate() - 30;
lastMonth.setDate(past);
return date >= lastMonth && date <= today;
}
function isLastYear(date) {
let lastYear = new Date();
let today = new Date();
let past = lastYear.getDate() - 365;
const today = new Date();
const past = lastYear.getDate() - 365;
lastYear.setDate(past);
return date >= lastYear && date <= today;
}
......@@ -48,15 +45,11 @@ window.addEventListener("DOMContentLoaded", async () => {
}
let workouts = await fetchWorkouts(ordering);
console.log(workouts.length);
for (let i = 0; i < workouts.length; i++) {
let workout = workouts[i];
let d = workout.date;
let wDate = new Date(d.slice(0, 4), d.slice(5, 7) - 1, d.slice(8, 10));
console.log("last week", isLastWeek(wDate));
console.log("last month", isLastMonth(wDate));
console.log("last year", isLastYear(wDate));
if (workout.owner == currentUser.url) {
if (isLastWeek(wDate)) {
......@@ -75,6 +68,5 @@ window.addEventListener("DOMContentLoaded", async () => {
document.getElementById("month").innerHTML = thirtyDays;
document.getElementById("year").innerHTML = threeSixtyFive;
console.log(sevenDays, thirtyDays, threeSixtyFive);
}
});
//single_test.js:Jest testing tutorial for Selenium JavaScript Testing
/**
* @jest-environment jest-environment-webdriver
*/
const webdriver = require('selenium-webdriver');
const script = require('jest');
const url = 'https://www.selenium.dev/'
const getElementXpath = async (driver, xpath, timeout = 3000) => {
const el = await driver.wait(until.elementLocated(By.xpath(xpath)), timeout);
return await driver.wait(until.elementIsVisible(el), timeout);
};
const getElementName = async (driver, name, timeout = 3000) => {
const el = await driver.wait(until.elementLocated(By.name(name)), timeout);
return await driver.wait(until.elementIsVisible(el), timeout);
};
const getElementId = async (driver, id, timeout = 3000) => {
const el = await driver.wait(until.elementLocated(By.id(id)), timeout);
return await driver.wait(until.elementIsVisible(el), timeout);
};
// declaring the test group This is our test case scenario that we will execute from our first test script.
describe('executing test scenario on the website www.selenium.dev', () => {
let driver;
driver = new webdriver().build();
// func to get the cloud driver eslint disable next line no undef
await driver.get(
https://www.selenium.dev’,
);
}, 10000);
afterAll(async () => {
await driver.quit();
}, 15000);
test('it performs a validation of title on the home page', async () => {
await browser.get(url)
const title = await browser.findElement(by.tagName('h1')).getText()
expect(title).toContain('SeleniumHQ Browser Automation')
})
test('it performs a validation of the search box on the page', async () => {
const foundAndLoadedCheck = async () => {
await until.elementLocated(by.id('search'))
const value = await browser.findElement(by.id('search')).getText()
return value !== '~'
}
await browser.wait(foundAndLoadedCheck, 3000)
const search = await browser.findElement(by.id('search')).getText()
expect(search).toEqual('')
})
// declaring the test group
describe('it captures a screenshot of the current page on the browser', () => {
test('snap a picture by taking the screenshot', async () => {
// files saved in ./reports/screenshots by default
await browser.get(url)
await browser.takeScreenshot()
})
})
})
\ No newline at end of file
......@@ -20,13 +20,13 @@ async function retrieveWorkout(id) {
let selector = `input[name="${key}"], textarea[name="${key}"]`;
let input = form.querySelector(selector);
let newVal = workoutData[key];
if (key == "date") {
if (key === "date") {
// Creating a valid datetime-local string with the correct local time
let date = new Date(newVal);
date = new Date(
date.getTime() - date.getTimezoneOffset() * 60 * 1000
).toISOString(); // get ISO format for local time
newVal = date.substring(0, newVal.length - 1); // remove Z (since this is a local time, not UTC)
).toISOString();
newVal = date.substring(0, newVal.length - 1);
}
if (key != "files") {
input.value = newVal;
......@@ -79,7 +79,7 @@ async function retrieveWorkout(id) {
for (let j = 0; j < exerciseTypes.count; j++) {
let option = document.createElement("option");
option.value = exerciseTypes.results[j].id;
if (currentExerciseTypeId == exerciseTypes.results[j].id) {
if (currentExerciseTypeId === exerciseTypes.results[j].id) {
currentExerciseType = exerciseTypes.results[j];
}
option.innerText = exerciseTypes.results[j].name;
......@@ -103,7 +103,7 @@ async function retrieveWorkout(id) {
let exerciseNumberLabel = divExerciseContainer.querySelector(
".exercise-number"
);
(exerciseNumberLabel.for = "for"), `inputNumber${i}`;
(exerciseNumberLabel.for = "for")`inputNumber${i}`;
exerciseNumberLabel.innerText = currentExerciseType.unit;
let exerciseNumberInput = divExerciseContainer.querySelector(
......@@ -129,9 +129,8 @@ function athleteChecked() {
let checkBox = document.getElementById("forAthlete");
let athletes = document.getElementById("athletes");
let myself = document.getElementById("inputOwner");
console.log(checkBox.checked);
if (checkBox.checked == true) {
if (checkBox.checked === true) {
athletes.style.display = "block";
myself.style.display = "none";
} else {
......@@ -151,7 +150,6 @@ async function athletesInDropdown() {
newElement.text = athlete.username;
ath.add(newElement);
}
click = true;
}
function handleEditWorkoutButtonClick() {
......@@ -160,7 +158,8 @@ function handleEditWorkoutButtonClick() {
setReadOnly(false, "#form-workout");
document.querySelector("#inputOwner").readOnly = true; // owner field should still be readonly
// owner field should still be readonly
document.querySelector("#inputOwner").readOnly = true;
editWorkoutButton.className += " hide";
okWorkoutButton.className = okWorkoutButton.className.replace(" hide", "");
......@@ -272,8 +271,6 @@ function handleCancelDuringWorkoutCreate() {
}
async function createBlankExercise() {
let form = document.querySelector("#form-workout");
let exerciseTypeResponse = await sendRequest("GET", `${HOST}/api/exercises/`);
let exerciseTypes = await exerciseTypeResponse.json();
......@@ -375,7 +372,7 @@ async function retrieveComments(workoutid) {
let comments = data.results;
for (let comment of comments) {
let splitArray = comment.workout.split("/");
if (splitArray[splitArray.length - 2] == workoutid) {
if (splitArray[splitArray.length - 2] === workoutid) {
addComment(comment.owner, comment.content, comment.timestamp, true);
}
}
......@@ -404,7 +401,7 @@ window.addEventListener("DOMContentLoaded", async () => {
await retrieveComments(id);
console.log(currentUser.url);
if (workoutData["owner"] == currentUser.url) {
if (workoutData["owner"] === currentUser.url) {
editWorkoutButton.classList.remove("hide");
editWorkoutButton.addEventListener("click", handleEditWorkoutButtonClick);
deleteWorkoutButton.addEventListener(
......
......@@ -27,13 +27,13 @@ async function fetchWorkouts(ordering) {
let rows = table.querySelectorAll("tr");
rows[0].querySelectorAll(
"td"
)[1].textContent = localDate.toLocaleDateString(); // Date
)[1].textContent = localDate.toLocaleDateString();
rows[1].querySelectorAll(
"td"
)[1].textContent = localDate.toLocaleTimeString(); // Time
rows[2].querySelectorAll("td")[1].textContent = workout.owner_username; //Owner
)[1].textContent = localDate.toLocaleTimeString();
rows[2].querySelectorAll("td")[1].textContent = workout.owner_username;
rows[3].querySelectorAll("td")[1].textContent =
workout.exercise_instances.length; // Exercises
workout.exercise_instances.length;
container.appendChild(aWorkout);
});
......@@ -52,7 +52,6 @@ window.addEventListener("DOMContentLoaded", async () => {
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.has("ordering")) {
let aSort = null;
ordering = urlParams.get("ordering");
if (ordering == "name" || ordering == "owner" || ordering == "date") {
let aSort = document.querySelector(`a[href="?ordering=${ordering}"`);
......@@ -76,12 +75,9 @@ window.addEventListener("DOMContentLoaded", async () => {
let tabEls = document.querySelectorAll('a[data-bs-toggle="list"]');
for (let i = 0; i < tabEls.length; i++) {
let tabEl = tabEls[i];
tabEl.addEventListener("show.bs.tab", function(event) {
tabEl.addEventListener("show.bs.tab", function (event) {
let workoutAnchors = document.querySelectorAll(".workout");
for (let j = 0; j < workouts.length; j++) {
// I'm assuming that the order of workout objects matches
// the other of the workout anchor elements. They should, given
// that I just created them.
let workout = workouts[j];
let workoutAnchor = workoutAnchors[j];
......@@ -117,5 +113,4 @@ window.addEventListener("DOMContentLoaded", async () => {
}
});
}
let templateWeek = document.querySelector("#template-workout");
});
{
"name": "secfit",
"description": "Secure Fitness",
"version": "0.0.1",
"main": "index.js",
"engines": {
"node": "12.x"
},
"dependencies": {
"cordova": "10.0.0",
"cordova-browser": "6.0.0",
"cordova-plugin-whitelist": "^1.3.4",
"form-data": "^4.0.0"
},
"devDependencies": {
"testcafe": "^1.12.0",
"testcafe-browser-provider-puppeteer": "^1.5.2"
}
}
This diff is collapsed.
......@@ -13,6 +13,7 @@
"form-data": "^4.0.0"
},
"devDependencies": {
"eslint": "^7.22.0",
"testcafe": "^1.12.0",
"testcafe-browser-provider-puppeteer": "^1.5.2"
}
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment