Skip to content
FrontDepth, Home

Back to the topic

Practice: Unit tests and test doubles

Answer first, then compare. Rate yourself honestly — it drives your weak-areas list.

3 predict-output · 4 open

Questions up to level

Shows questions up to the selected level.

No practice questions for this level yet.

  1. Predict the outputJunior

    Vitest is not used here: equals is a simplified plain-JS model of how Vitest's toEqual and toStrictEqual compare plain objects, arrays and class instances, and toBe uses Object.is, as Vitest's does. Each function returns true where the Vitest matcher would pass. What does the code log?

    JavaScript
    // a simplified model of Vitest's equality rules for plain objects, arrays and classes
    function equals(a, b, strict) {
      if (Object.is(a, b)) return true;
      if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
      if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false;
      const keysA = Object.keys(a).filter((k) => strict || a[k] !== undefined);
      const keysB = Object.keys(b).filter((k) => strict || b[k] !== undefined);
      if (keysA.length !== keysB.length) return false;
      return keysA.every((k) => Object.hasOwn(b, k) && equals(a[k], b[k], strict));
    }
    
    const toBe = (a, b) => Object.is(a, b);
    const toEqual = (a, b) => equals(a, b, false);
    const toStrictEqual = (a, b) => equals(a, b, true);
    
    class Point {
      constructor(x, y) {
        this.x = x;
        this.y = y;
      }
    }
    
    const saved = { id: 7, tags: ["new"] };
    const loaded = { id: 7, tags: ["new"] };
    
    console.log(toBe(saved, loaded), toEqual(saved, loaded), toBe(saved.id, loaded.id));
    console.log(toEqual(new Point(1, 2), { x: 1, y: 2 }), toStrictEqual(new Point(1, 2), { x: 1, y: 2 }));
    console.log(toEqual({ id: 7, note: undefined }, { id: 7 }), toStrictEqual({ id: 7, note: undefined }, { id: 7 }));
    console.log(toBe(NaN, NaN), toBe(0.1 + 0.2, 0.3));
  2. Open questionJunior

    When do you use toBe, toEqual and toStrictEqual, and how do you correctly test a function that throws and a function that returns a promise?

    Think it through first

    Answer out loud or in your head as if you were in an interview, then reveal.

  3. Predict the outputMiddle

    This is not Vitest: fn is a simplified plain-JS model of vi.fn, following the documented rules for mockReturnValue, mockReturnValueOnce, mockClear and mockReset. The mock starts with the implementation () => 1.7. What does the code log?

    JavaScript
    // a simplified model of vi.fn: once-values, a default value, clear and reset
    function fn(original) {
      let impl = original;
      let once = [];
      const mock = (...args) => {
        mock.mock.calls.push(args);
        const next = once.length > 0 ? once.shift() : impl;
        return next ? next(...args) : undefined;
      };
      mock.mock = { calls: [] };
      mock.mockReturnValue = (value) => {
        impl = () => value;
        return mock;
      };
      mock.mockReturnValueOnce = (value) => {
        once.push(() => value);
        return mock;
      };
      mock.mockClear = () => {
        mock.mock = { calls: [] };
        return mock;
      };
      mock.mockReset = () => {
        mock.mock = { calls: [] };
        once = [];
        impl = original;
        return mock;
      };
      return mock;
    }
    
    const getRate = fn(() => 1.7);
    getRate.mockReturnValue(2).mockReturnValueOnce(5).mockReturnValueOnce(6);
    
    console.log(getRate("USD"), getRate("USD"), getRate("USD"), getRate("USD"));
    console.log(getRate.mock.calls.length);
    
    getRate.mockClear();
    console.log(getRate("EUR"), getRate.mock.calls.length);
    
    getRate.mockReset();
    console.log(getRate("EUR"), getRate.mock.calls.length);
  4. Open questionMiddle

    A function reads the current time, applies discount rules and posts an order to the API. How would you change it so that its rules can be unit-tested without mocking modules?

    Think it through first

    Answer out loud or in your head as if you were in an interview, then reveal.

  5. Open questionMiddle

    What kinds of test doubles are there, and what is the difference between state verification and behaviour verification?

    Think it through first

    Answer out loud or in your head as if you were in an interview, then reveal.

  6. Predict the outputSenior

    Plain JS, no Vitest. lineTotal receives its data source as a parameter. A unit test passes it a hand-written stub; production passes the real client. The fromStub === 36 check stands in for expect(fromStub).toBe(36). What does the code log?

    JavaScript
    // the real client, as the API actually responds
    function fetchProduct(id) {
      return { id, unitPrice: 12, currency: "AZN" };
    }
    
    // the code under test reads a field that the API does not have
    function lineTotal(getProduct, id, quantity) {
      const product = getProduct(id);
      return product.price * quantity;
    }
    
    // a hand-written stub, shaped after the code instead of the API
    const stubProduct = (id) => ({ id, price: 12 });
    
    const fromStub = lineTotal(stubProduct, "p1", 3);
    console.log(fromStub, fromStub === 36 ? "pass" : "fail");
    
    const fromReal = lineTotal(fetchProduct, "p1", 3);
    console.log(fromReal, Number.isNaN(fromReal));
  7. Open questionSenior

    In a pull request, a test for checkout() mocks the project's cart store, pricing module and API client with vi.mock, stubs their return values and asserts only toHaveBeenCalledWith on each. What would you say in the review, and how would you rewrite the test?

    Think it through first

    Answer out loud or in your head as if you were in an interview, then reveal.