Security-Oriented Tests
Build a working model of automated testing from assertions to unit, component, API, integration, contract and end-to-end tests, then apply it to a single progressive task-board capstone where each milestone adds a real defect, a failing test, a corrected implementation and an expected result.
What you will be able to do
#- Test input validation against hostile input.
- Verify that untrusted content is escaped before rendering.
- Recognize what a security test can and cannot prove.
Overview
#Security tests are negative tests with hostile input
A security test feeds input an attacker would use and asserts the code handles it safely. It is a negative test with a specific adversary in mind: script tags, path traversal, oversized payloads, and unexpected types.
Input validation
Test that validation rejects malformed and hostile input rather than passing it through. A length limit, an allow-list of characters, and a type check each deserve a test with input that violates them. A validation function that accepts a 10-megabyte string is a denial-of-service risk.
function isSafeSlug(slug) {
return /^[a-z0-9-]{1,64}$/.test(slug);
}
Output escaping
Injection happens when untrusted data is placed into a context that interprets it, such as HTML or SQL. Test that user content rendered into the page is escaped, so a <script> in a task title appears as text, not as executable script. Assert on the escaped output, not on the absence of a crash.
Do not build your own sanitizer
If the test needs to prove that HTML is safe, assert that the code uses a vetted sanitizer or escapes by default, rather than writing a regex that tries to strip tags. Regex-based sanitizers are a classic source of bypasses. The test should verify the safe path is used, not reimplement safety.
What a security test proves
A security test proves that a specific hostile input is handled safely by a specific code path. It does not prove the application is secure. Security is a property of the whole system, and tests are one layer among threat modeling, dependency scanning and review. Be precise about the boundary: a passing injection test is evidence for that input, not a security guarantee.
Environment and secrets
Security tests run against test fixtures and fake credentials, never production data or real secrets. A test that needs a real token is a test that will leak it. Use fakes and assert that secrets are never logged or returned in error responses.
Dependency and configuration checks
Some security defects live in dependencies or configuration, not in your code. A dependency audit and a check that security headers are present are tests too. They run in CI as part of the gate, not in a browser sandbox.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
What does `isSafeSlug('<script>')` return?
Read the code, then choose the best answer. The reference explanation stays hidden until you respond. stimulus.javascriptfunction isSafeSlug(slug) { return /^[a-z0-9-]{1,64}$/.test(slug); } console.log(isSafeSlug('<script>'));Exercise 2Explain
Explain why a passing injection test does not prove the application is secure.
Reveal the reference answer
reference.javascriptThe test exercises one input against one code path. It proves that input is handled safely there, but not that other inputs, other paths or other contexts are safe. Injection can occur in HTML, attributes, URLs, SQL and logs, each with different rules. Security is a property of the whole system, so a single test is evidence for a specific case, not a guarantee. Threat modeling, review and dependency scanning cover the rest.The answer should scope the evidence to the tested input and path and name the other layers of security work.
Exercise 3Implement
Implement `escapeHtml(text)` that replaces &, <, >, double quote and single quote with their HTML entities. `console.log(escapeHtml('<b>&"x"</b>'))` should print `<b>&"x"</b>`.
starter.javascriptfunction escapeHtml(text) { // your code here }Reveal the reference answer
reference.javascriptfunction escapeHtml(text) { return text .replace(/&/g, '&') .replace(/</g, '<') .replace(/>/g, '>') .replace(/"/g, '"') .replace(/'/g, '''); }Authored expected output: <b>&"x"</b>
Each special character is replaced with its entity. The ampersand is replaced first so the entities introduced by later replacements are not double-escaped. The result renders as literal text, not markup.
Exercise 4Debug
This 'sanitizer' is bypassable because it only removes lowercase script tags. Fix the test approach by escaping instead of stripping.
starter.javascriptfunction sanitize(html) { return html.replace(/<script>/g, ''); } console.log(sanitize('<SCRIPT>alert(1)</SCRIPT>'));Reveal the reference answer
reference.javascriptfunction escapeHtml(text) { return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'); } console.log(escapeHtml('<SCRIPT>alert(1)</SCRIPT>'));Authored expected output: <SCRIPT>alert(1)</SCRIPT>
Stripping only the exact lowercase tag leaves uppercase and malformed variants dangerous. Escaping every angle bracket neutralizes all tag variants at once, which is why escaping beats stripping.
Exercise 5Test
Write tests that prove `escapeHtml` neutralizes a script tag and preserves ordinary text.
starter.javascriptfunction escapeHtml(text) { return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, '''); }Reveal the reference answer
reference.javascriptfunction assertEqual(actual, expected, label) { if (actual !== expected) throw new Error(label + ': expected ' + expected + ' but got ' + actual); } assertEqual(escapeHtml('<script>alert(1)</script>').includes('<script>'), false, 'no raw script tag'); assertEqual(escapeHtml('hello').includes('<'), false, 'plain text unchanged'); assertEqual(escapeHtml('a & b'), 'a & b', 'ampersand escaped'); console.log('escaping verified');Authored expected output: escaping verified
The first assertion proves the hostile tag no longer appears raw. The second proves ordinary text is untouched. The third pins the ampersand escaping, which prevents double-escaping defects.
Exercise 6Interview
In an interview, explain how you test that user input is rendered safely.
Reveal the reference answer
reference.javascriptI feed hostile input such as a script tag and an attribute-breaking quote into the field, then assert that the rendered output contains the escaped text and not the raw markup. I assert that the code uses a vetted escaping or sanitizing path rather than a hand-rolled regex stripper. I test the same input in each context it can reach, such as text, an attribute and a URL. I am explicit that this proves those cases, not that the app is secure, and I keep the tests on fake data with no real secrets.The answer should cover hostile input, escaped output, vetted sanitizers, multiple contexts, and an honest evidence boundary.
Common misconceptions
#- A passing injection test proves the application is secure.
- A regex that strips script tags is a safe sanitizer.
- Security tests need real credentials to be realistic.
Follow-up practice
#- testing-ci-gates
- testing-test-strategy
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.