Testing React Components with RTL
Content
💭 Practice exercises are optional and do not need to be submitted
Write a function celsiusToFahrenheit(celsius) that converts a Celsius temperature to Fahrenheit, rounded to one decimal place. Then write thorough unit tests for it.
celsiusToFahrenheit(0); // returns 32
celsiusToFahrenheit(100); // returns 212
celsiusToFahrenheit(37); // returns 98.6
Write at least four tests: the happy path, a negative number, a value that needs rounding, and zero.
💡 Hint:
Math.round(value * 10) / 10rounds a number to one decimal place.
Before you use TDD on the real assignment, practise the red-green-refactor cycle on something small and self-contained.
Write getPasswordStrength(password), which returns "weak", "medium", or "strong", using these rules:
"weak""medium""strong"getPasswordStrength("abc"); // "weak"
getPasswordStrength("abcdefgh"); // "medium"
getPasswordStrength("Abcd3fg!"); // "strong"
Write a failing test for each rule before you write any implementation.
Questions to consider:
⚠️ Resist the urge to write
getPasswordStrengthfirst. Write one failing test, watch it fail, then write just enough code to make it pass.
Given this component:
type Props = {
label: string;
onClick: () => void;
disabled?: boolean;
};
export function Button({ label, onClick, disabled }: Props) {
return (
<button onClick={onClick} disabled={disabled}>
{label}
</button>
);
}
Write tests that:
getByRole, never a class name or test idonClick fires when a user clicks it, using userEventonClick does not fire when disabled is true💡 If you would like to practice more then remember that you can ask AI to generate more exercises for you!
The HackYourFuture curriculum is licensed under CC BY-NC-SA 4.0 *https://hackyourfuture.net/*

Built with ❤️ by the HackYourFuture community · Thank you, contributors
Found a mistake or have a suggestion? Let us know in the feedback form.