Course contentsShow
← TypeScript
Lesson 935 of 1,79621. The unknown TypeFree lesson

Testing API Parsing with Mock unknown Data

Write tests that pass malformed unknown data to ensure validators catch all edge cases.

Testing API Parsing with Mock unknown Data

What you'll learn: How to write tests that deliberately pass malformed, incomplete, and unexpected unknown data to your validators to ensure they catch every possible edge case before bad data reaches your application.

The Testing Philosophy

You've built type guards and validators to safely parse unknown API data. But how do you know they actually work? The best way to build confidence is to attack your validators with intentionally broken data—the kind of chaos the real world will throw at you.

Think of it like stress-testing a bridge: you don't just drive normal cars over it. You simulate earthquakes, overloading, and extreme weather to find weak points before disaster strikes.

Writing Tests for the Happy Path (Not Enough)

function isUser(data: unknown): data is { id: number; name: string } {
  return (
    typeof data === "object" &&
    data !== null &&
    "id" in data &&
    typeof (data as any).id === "number" &&
    "name" in data &&
    typeof (data as any).name === "string"
  );
}

// ❌ Weak test - only happy path
const validUser = { id: 1, name: "Alice" };
console.log(isUser(validUser)); // true - but what about edge cases?

Testing the Unhappy Paths (The Real Work)

// ✅ Comprehensive test suite
const malformedTests = [
  null,                           // null value
  undefined,                      // undefined
  42,                             // primitive instead of object
  "user data",                    // string
  [],                             // array instead of object
  { id: "123", name: "Bob" },     // id is string not number
  { id: 1 },                      // missing name
  { name: "Charlie" },            // missing id
  { id: 1, name: 42 },            // name is number not string
  { id: null, name: "Dave" },     // id is null
  { id: 1, name: null },          // name is null
  { id: NaN, name: "Eve" },       // id is NaN
  { id: 1, name: "" },            // empty string (valid but test anyway)
];

malformedTests.forEach((test, i) => {
  const result = isUser(test);
  console.log(`Test ${i}: ${result === false ? "✓" : "✗ FAILED"}`);
});

Catching Real-World Nightmares

function parseApiResponse(data: unknown): { id: number; name: string } {
  if (!isUser(data)) {
    throw new Error("Invalid user data");
  }
  return data;
}

// Test cases that mirror real API failures:
const edgeCases = [
  {},                                    // Empty object from server error
  { id: 1.5, name: "Test" },            // Float instead of integer
  { id: Infinity, name: "Test" },       // Infinity
  { id: -1, name: "Test" },             // Negative ID (business logic)
  { id: 1, name: "Test", extra: true }, // Extra fields (usually OK)
];

edgeCases.forEach(testCase => {
  try {
    parseApiResponse(testCase);
    console.log("Parsed:", testCase);
  } catch (e) {
    console.log("Rejected:", testCase, "->", (e as Error).message);
  }
});

The Pattern: Exhaustive Edge Case Coverage

The goal is to test every branch of your type guards:

  • Every typeof check
  • Every null check
  • Every property existence check
  • Every nested validation

If your validator has 5 conditions, you need at least 5 tests that fail each one individually, plus combined failures.

Key Takeaway: Tests with deliberately malformed unknown data reveal validator weaknesses before production failures. Your validators are only as good as the edge cases you've tested them against.