Test with Jest
Project Structure
my-site/
├── index.html
├── script.js
├── script.test.js
├── package.json
└── jest.config.js
You can copy paste the code of each part present below and tried it out with the commands shown in the end of this page
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple Greeting App</title>
</head>
<body>
<h1>Greeting App</h1>
<input type="text" id="nameInput" placeholder="Enter your name" />
<button onclick="showGreeting()">Greet</button>
<p id="greetingOutput"></p>
<script src="script.js"></script>
</body>
</html>
script.js
function generateGreeting(name) {
if (!name.trim()) return "Hello, stranger!";
return `Hello, ${name.trim()}!`;
}
function showGreeting() {
const input = document.getElementById("nameInput").value;
const output = document.getElementById("greetingOutput");
output.textContent = generateGreeting(input);
}
// Export for testing
if (typeof module !== "undefined") {
module.exports = { generateGreeting };
}
script.test.js
const { generateGreeting } = require('./script');
describe('generateGreeting', () => {
test('greets a user by name', () => {
expect(generateGreeting('Alice')).toBe('Hello, Alice!');
});
test('trims spaces from name', () => {
expect(generateGreeting(' Bob ')).toBe('Hello, Bob!');
});
test('handles empty input', () => {
expect(generateGreeting('')).toBe('Hello, stranger!');
});
test('handles whitespace-only input', () => {
expect(generateGreeting(' ')).toBe('Hello, stranger!');
});
});
package.json
{
"name": "greeting-site",
"version": "1.0.0",
"scripts": {
"test": "jest"
},
"devDependencies": {
"jest": "^29.0.0"
}
}
jest.config.js
module.exports = {
testEnvironment: "node"
};
In order to run it, open your terminal and run the commands below:
npm init -y
npm install --save-dev jest
npm test