Bird
Raised Fist0
Denoframework~15 mins

Assertions and matchers in Deno - Deep Dive

Choose your learning style10 modes available
Overview - Assertions and matchers
What is it?
Assertions and matchers are tools used in testing code to check if the program behaves as expected. Assertions are statements that say, "This must be true," and if not, the test fails. Matchers are helpers that describe the exact condition or value we expect in a test. Together, they help catch mistakes early by verifying code results automatically.
Why it matters
Without assertions and matchers, developers would have to check program results by hand, which is slow and error-prone. They make testing faster, more reliable, and easier to understand. This means bugs get found sooner, saving time and frustration. In real life, it's like having a safety net that catches mistakes before they cause problems.
Where it fits
Before learning assertions and matchers, you should understand basic programming and how to write simple tests. After mastering them, you can explore advanced testing techniques like mocking, test coverage, and continuous integration. This topic is a key step in becoming confident in writing reliable software.
Mental Model
Core Idea
Assertions and matchers are like checkpoints that automatically verify if your code's output matches what you expect.
Think of it like...
Imagine you are baking cookies and have a checklist: 'Are they golden brown?' 'Are they soft inside?' Each assertion is like checking one item on the list to make sure the cookies turned out right.
┌───────────────┐
│   Test Code   │
└──────┬────────┘
       │ runs
       ▼
┌───────────────┐
│  Assertion &  │
│   Matcher     │
└──────┬────────┘
       │ checks
       ▼
┌───────────────┐
│ Test Pass/Fail│
└───────────────┘
Build-Up - 7 Steps
1
FoundationWhat is an Assertion in Testing
🤔
Concept: Introduce the basic idea of an assertion as a statement that must be true for a test to pass.
An assertion is a simple check in your test code. For example, you might write `assertEquals(2 + 2, 4)` to say that adding 2 and 2 should equal 4. If this is true, the test passes; if not, it fails and shows an error.
Result
The test will pass if the condition is true, or fail with a clear message if false.
Understanding assertions is the foundation of automated testing because they define what 'correct' means in code.
2
FoundationBasic Matchers in Deno Testing
🤔
Concept: Explain matchers as helpers that describe expected values or conditions in assertions.
Matchers are functions like `assertEquals`, `assert`, or `assertStringIncludes` that check specific conditions. For example, `assertStringIncludes('hello world', 'world')` checks if one string contains another. They make tests clearer and more precise.
Result
Tests become easier to write and read, with clear intent about what is being checked.
Knowing matchers helps you write tests that communicate exactly what you expect from your code.
3
IntermediateUsing Assertions with Different Data Types
🤔Before reading on: do you think assertEquals works the same for numbers, strings, and objects? Commit to your answer.
Concept: Show how assertions handle various data types and what to watch out for.
In Deno, `assertEquals` compares values deeply. For numbers and strings, it checks equality directly. For objects or arrays, it compares their contents, not just references. For example, `assertEquals({a:1}, {a:1})` passes, but `assertEquals({a:1}, {a:2})` fails.
Result
Tests correctly verify complex data structures, not just simple values.
Understanding deep equality prevents false test failures or passes when working with objects or arrays.
4
IntermediateCustomizing Error Messages in Assertions
🤔Before reading on: do you think adding custom messages to assertions helps debugging? Commit to your answer.
Concept: Teach how to add helpful messages to assertions for clearer test failure explanations.
Deno assertions accept an optional message parameter. For example, `assertEquals(result, expected, 'Result did not match expected value')`. When a test fails, this message appears, making it easier to find the problem.
Result
Test failures provide clear, meaningful information, speeding up debugging.
Knowing how to add messages makes tests more maintainable and developer-friendly.
5
IntermediateCombining Multiple Matchers in Tests
🤔Before reading on: do you think you can use multiple assertions in one test function? Commit to your answer.
Concept: Explain how to use several assertions together to test different aspects of code behavior.
A single test can have many assertions. For example, you can check a function's output type, value, and side effects all in one test. This helps ensure thorough testing without writing many separate tests.
Result
Tests become more comprehensive and efficient.
Using multiple assertions in one test balances thoroughness with simplicity.
6
AdvancedWriting Custom Matchers in Deno
🤔Before reading on: do you think you can create your own matcher functions? Commit to your answer.
Concept: Show how to build custom matchers for specialized checks not covered by built-in ones.
You can write functions that throw errors when conditions fail, acting as custom matchers. For example, a matcher to check if a number is even: `function assertIsEven(num) { if (num % 2 !== 0) throw new Error('Number is not even'); }`. Use these in tests like built-in matchers.
Result
Tests can cover unique conditions specific to your application.
Creating custom matchers extends testing power beyond defaults, making tests more expressive.
7
ExpertHow Assertions Integrate with Deno's Test Runner
🤔Before reading on: do you think assertions stop test execution immediately on failure? Commit to your answer.
Concept: Explain how assertions work inside Deno's test runner and affect test flow and reporting.
When an assertion fails, it throws an error that stops the current test function. Deno's test runner catches this and marks the test as failed, showing the error message and stack trace. Tests run independently, so one failure doesn't stop others. This design helps isolate problems and provides clear feedback.
Result
Tests fail fast and report precise errors without affecting unrelated tests.
Understanding this flow helps write tests that are reliable and easy to debug in large projects.
Under the Hood
Assertions in Deno are functions that check conditions and throw errors if those conditions are false. When a test runs, these errors signal failure to the test runner, which collects results and displays them. Matchers are specialized assertion functions that encapsulate common checks, improving readability and reusability. Internally, deep equality checks compare object structures recursively to ensure accurate comparisons.
Why designed this way?
Deno's assertion system was designed for simplicity and clarity, using JavaScript's native error throwing to signal failures. This avoids complex state management and leverages existing language features. Matchers provide a clear, expressive API to cover common testing needs without extra dependencies. Alternatives like returning boolean values were rejected because they complicate test flow and error reporting.
┌───────────────┐
│   Test Code   │
└──────┬────────┘
       │ calls
       ▼
┌───────────────┐
│  Assertion    │
│  Function     │
└──────┬────────┘
       │ throws error if false
       ▼
┌───────────────┐
│  Error Thrown │
└──────┬────────┘
       │ caught by
       ▼
┌───────────────┐
│ Test Runner   │
│  Reports      │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does assertEquals check if two objects are the same instance or just have the same content? Commit to your answer.
Common Belief:assertEquals only checks if two objects are the exact same instance in memory.
Tap to reveal reality
Reality:assertEquals performs a deep equality check, comparing the contents of objects, not just their memory references.
Why it matters:Believing this causes tests to fail unexpectedly when comparing different but identical objects, leading to confusion and wasted debugging time.
Quick: Do assertions continue running after one fails in a test? Commit to your answer.
Common Belief:All assertions in a test run even if one fails, so you get all errors at once.
Tap to reveal reality
Reality:When an assertion fails, it throws an error that stops the current test immediately; later assertions in the same test do not run.
Why it matters:Expecting all assertions to run can lead to misunderstanding test results and missing the root cause of failure.
Quick: Can you use assertions outside of test functions safely? Commit to your answer.
Common Belief:Assertions can be used anywhere in code without issues, even outside tests.
Tap to reveal reality
Reality:Assertions are meant for tests; using them in production code can cause unexpected crashes if conditions fail.
Why it matters:Misusing assertions outside tests can cause program instability and poor user experience.
Quick: Are custom matchers always necessary for testing complex conditions? Commit to your answer.
Common Belief:You must write custom matchers for any complex test condition.
Tap to reveal reality
Reality:Often, combining built-in matchers suffices; custom matchers are only needed for very specific or repeated checks.
Why it matters:Overusing custom matchers adds unnecessary complexity and maintenance burden.
Expert Zone
1
Some matchers perform shallow equality checks while others do deep checks; knowing which to use avoids subtle bugs.
2
Assertions can be combined with async/await in Deno tests to handle asynchronous code elegantly.
3
Custom matchers can improve test readability but should be designed to fail with clear, actionable messages.
When NOT to use
Assertions and matchers are not suitable for performance-critical production code paths or for validating user input at runtime. Instead, use explicit error handling or validation libraries designed for production safety.
Production Patterns
In real-world Deno projects, assertions are used extensively in unit and integration tests. Teams often create shared custom matchers for domain-specific checks. Tests are run automatically in CI pipelines to catch regressions early. Assertions are combined with mocks and spies for complex behavior verification.
Connections
Unit Testing
Assertions and matchers are fundamental tools used within unit testing frameworks.
Understanding assertions deeply helps write better unit tests that precisely verify small pieces of code.
Error Handling
Assertions use error throwing to signal test failures, linking them to error handling mechanisms.
Knowing how assertions throw and propagate errors clarifies how test runners detect and report failures.
Quality Control in Manufacturing
Assertions and matchers function like quality checks on a production line, ensuring each product meets standards.
Seeing tests as quality gates helps appreciate their role in maintaining software reliability and preventing defects.
Common Pitfalls
#1Using assertEquals to compare objects but expecting reference equality.
Wrong approach:assertEquals(obj1, obj2); // expecting true only if same instance
Correct approach:assertEquals(obj1, obj2); // correctly checks deep equality of contents
Root cause:Misunderstanding that assertEquals compares object references rather than their content.
#2Writing multiple assertions in a test but expecting all to run even if one fails.
Wrong approach:assert(condition1); assert(condition2); // second runs even if first fails
Correct approach:assert(condition1); // test stops if fails // separate tests for condition2
Root cause:Not knowing that assertions throw errors that stop test execution immediately.
#3Not providing custom messages in assertions, making failures hard to diagnose.
Wrong approach:assertEquals(result, expected);
Correct approach:assertEquals(result, expected, 'Result did not match expected value');
Root cause:Overlooking the value of descriptive failure messages for debugging.
Key Takeaways
Assertions and matchers are essential tools that automatically check if code behaves as expected during tests.
Matchers provide clear, reusable ways to express what conditions your code should meet, improving test clarity.
Understanding deep equality in assertions prevents common mistakes when comparing complex data like objects and arrays.
When an assertion fails, it throws an error that stops the current test, helping isolate problems quickly.
Custom matchers extend testing capabilities but should be used thoughtfully to keep tests simple and maintainable.

Practice

(1/5)
1. What is the main purpose of assertions in Deno testing?
easy
A. To create new variables automatically
B. To check if the code behaves as expected
C. To speed up the execution of code
D. To format the output of the program

Solution

  1. Step 1: Understand what assertions do

    Assertions are used to verify that the code produces the expected results during tests.
  2. Step 2: Identify the purpose in testing

    They help catch errors by comparing actual output with expected output.
  3. Final Answer:

    To check if the code behaves as expected -> Option B
  4. Quick Check:

    Assertions verify behavior = D [OK]
Hint: Assertions verify expected behavior in tests [OK]
Common Mistakes:
  • Thinking assertions format output
  • Believing assertions speed up code
  • Confusing assertions with variable creation
2. Which of the following is the correct syntax to assert equality in Deno tests?
easy
A. assertEquals(actual, expected);
B. assertEqual(actual, expected);
C. assert.equal(actual, expected);
D. assertEquals(expected, actual);

Solution

  1. Step 1: Recall Deno's assertion function names

    Deno provides an assertion function called assertEquals to check equality.
  2. Step 2: Check parameter order and spelling

    The correct order is assertEquals(actual, expected), matching assertEquals(actual, expected); exactly.
  3. Final Answer:

    assertEquals(actual, expected); -> Option A
  4. Quick Check:

    Correct function and order = A [OK]
Hint: Use assertEquals(actual, expected) exactly [OK]
Common Mistakes:
  • Swapping actual and expected parameters
  • Using assertEqual instead of assertEquals
  • Using dot notation incorrectly
3. What will be the result of this Deno test code?
import { assertEquals } from "https://deno.land/std/testing/asserts.ts";

const result = 5 + 3;
assertEquals(result, 8);
medium
A. Runtime error because result is undefined
B. Test fails with an assertion error
C. Syntax error due to import statement
D. Test passes without errors

Solution

  1. Step 1: Evaluate the calculation

    The variable result is assigned 5 + 3, which equals 8.
  2. Step 2: Check the assertion

    The assertion compares result (8) with expected value 8, so it matches and passes.
  3. Final Answer:

    Test passes without errors -> Option D
  4. Quick Check:

    5 + 3 = 8 matches expected = A [OK]
Hint: Check calculation matches expected value exactly [OK]
Common Mistakes:
  • Assuming import causes syntax error
  • Thinking assertion fails when values match
  • Confusing runtime error with assertion failure
4. Identify the error in this Deno test code:
import { assertEquals } from "https://deno.land/std/testing/asserts.ts";

const value = "hello";
assertEquals(value, Hello);
medium
A. Missing quotes around Hello causing a ReferenceError
B. Incorrect import URL for assertEquals
C. assertEquals requires three arguments
D. Variable value is not defined

Solution

  1. Step 1: Check the assertion parameters

    The second parameter is Hello without quotes, so JavaScript treats it as a variable.
  2. Step 2: Identify the error caused

    Since Hello is not defined, this causes a ReferenceError at runtime.
  3. Final Answer:

    Missing quotes around Hello causing a ReferenceError -> Option A
  4. Quick Check:

    String literals need quotes = C [OK]
Hint: Always quote string literals in assertions [OK]
Common Mistakes:
  • Forgetting quotes around strings
  • Assuming import URL is wrong
  • Thinking assertEquals needs more arguments
5. You want to test if a function returns an array containing the number 10. Which assertion is best to use in Deno?
hard
A. assert(result == [10]);
B. assertEquals(result, 10);
C. assertEquals(result.includes(10), true);
D. assert(result.contains(10));

Solution

  1. Step 1: Understand the goal

    You want to check if the array contains the number 10, not if it equals 10 or a single-element array.
  2. Step 2: Evaluate each option

    assertEquals(result.includes(10), true); uses result.includes(10) which returns true if 10 is in the array, then asserts it equals true. This is correct.
    assert(result == [10]); compares array to [10] with == which fails because arrays are reference types.
    assertEquals(result, 10); compares array to number 10, which is incorrect.
    assert(result.contains(10)); uses contains which is not a valid JavaScript method.
  3. Final Answer:

    assertEquals(result.includes(10), true); -> Option C
  4. Quick Check:

    Use includes() to check array contents = B [OK]
Hint: Use includes() method inside assertEquals for array checks [OK]
Common Mistakes:
  • Using == to compare arrays
  • Using non-existent contains() method
  • Comparing array directly to a number
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard