DEV Community

Kush Bhandari
Kush Bhandari

Posted on

Implementing a Custom jest-like toBe() Matcher (Interview Question)

In a recent frontend interview, I was asked to implement a simplified version of Jest's toBe() matcher. The goal was to replicate the following behavior:

expect(5).toBe(5)        // true
expect(5).not.toBe(4)    // true
expect(5).toBe(10)       // false + error
Enter fullscreen mode Exit fullscreen mode

This question is less about Jest itself and more about JavaScript fundamentals, especially closures, API design, and error handling.

function expect(received) {
  function toBe(expected, isNot = false) {
    const pass = received === expected;

    if (isNot ? !pass : pass) {
      return true;
    }

    throw new Error(
      isNot
        ? `Expected ${received} not to be ${expected}`
        : `Expected ${received} to be ${expected}`
    );
  }

  return {
    toBe(expected) {
      return toBe(expected);
    },
    not: {
      toBe(expected) {
        return toBe(expected, true);
      }
    }
  };
}
Enter fullscreen mode Exit fullscreen mode

How It Works
Closures are used to retain the received value inside render
toBe() performs a strict equality check
.not simply flips the assertion logic
Errors are thrown to signal test failures, just like real test runners

Key Takeaway
Testing libraries like Jest are built on simple JavaScript principles. If you understand closures and function composition, you can easily reason about how these tools work internally - an essential skill for senior frontend developers.

Top comments (0)