'How do you test a form upon the submission addEventListener with jest without a framework only vanilla JS
Most of the research I have done in regards to jest testing unit testing and/or integration testing is all heavily geared towards React. But I am not using react on this project, using vanilla javascript. So the problem is I have no idea on how to write a test for this simple form that checks the input values and saves them to a variable.
How do I write a test for this form below using jest? or using JSDOM?
index.js
const form = document.querySelector('form');
// input[name="type"] I have 3 inputs with attributes of: name, email and card
//So I want their values when form is submitted.. Code works but No idea on how to write test for this.
const newValue = (type) => document.querySelector(`input[name="${type}"]`).value;
const clearInput = (type) => document.querySelector(`input[name="${type}"]`).value = '';
// How do I write a test for this form.addEventListener ??
form.addEventListener("submit", (e) => {
// vanilla js I prevent the page to reloa d upon form submission
e.preventDefault();
// building helper arrays for the incoming logic
const resultArray = [];
const arrayTypes = ['name', 'email', 'card']
// Looping through with for of on arrayTypes then sending each type to their relative helper function
for (const type of arrayTypes) {
resultArray.push(newValue(type))
clearInput(type)
}
// Assigning the respected Object key to each object key so that the backend can work accordingly
let obj = Object.assign({}, resultArray);
let { 0: name, 1: email, 2: card } = obj;
obj = { name, email, card };
return obj;
});
Here is a sample for the HTML form:
<form action="">
<div class="flex">
<label for="name">Name:</label>
<input value="" type="text" name="name" id="name" placeholder="Enter Your Name"/>
</div>
<div class="flex">
<label for="email">Email:</label>
<input value="" type="email" name="email" id="email" placeholder="Enter Your Email"/>
</div>
<div class="flex">
<label for="card">Card:</label>
<input value="" type="number" name="card" id="card" placeholder="Enter a Proxy Credit Card Number"/>
</div>
<div>
<input id="submit" type="submit" value="Submit"/>
</div>
</form>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
