Əsas məzmuna keç
FrontDepth, Ana səhifə

Mövzuya qayıt

Məşq: Unit testlər və test double-lar

Əvvəlcə cavab ver, sonra müqayisə et. Özünü dürüst qiymətləndir — zəif yerlərin siyahısı buna əsasən qurulur.

3 nəticə sualı · 4 açıq sual

Sualların səviyyəsi

Seçilmiş səviyyəyə qədər olan suallar göstərilir.

Bu səviyyə üçün hələ məşq sualı yoxdur.

  1. Nəticəni təxmin etJunior

    Burada Vitest istifadə olunmur: equals Vitest-in toEqual və toStrictEqual matcher-lərinin adi obyektləri, massivləri və class instance-larını necə müqayisə etdiyinin sadələşdirilmiş adi JS modelidir, toBe isə Vitest-dəki kimi Object.is-dən istifadə edir. Hər funksiya Vitest matcher-inin keçəcəyi halda true qaytarır. Kod konsola nə çıxaracaq?

    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. Açıq sualJunior

    toBe, toEqual və toStrictEqual-dan nə vaxt istifadə edirsən və xəta atan funksiyanı, eləcə də promise qaytaran funksiyanı necə düzgün test edirsən?

    Əvvəlcə özün düşün

    Müsahibədə olduğun kimi cavabı ucadan və ya içində söylə, sonra aç.

  3. Nəticəni təxmin etMiddle

    Bu, Vitest deyil: fn vi.fn-in sadələşdirilmiş adi JS modelidir və mockReturnValue, mockReturnValueOnce, mockClear və mockReset üçün sənədlərdə yazılmış qaydalara əməl edir. Mock () => 1.7 implementasiyası ilə yaradılır. Kod konsola nə çıxaracaq?

    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. Açıq sualMiddle

    Funksiya cari vaxtı oxuyur, endirim qaydalarını tətbiq edir və sifarişi API-yə göndərir. Onun qaydalarını modulları mock etmədən unit test etmək üçün funksiyanı necə dəyişərdin?

    Əvvəlcə özün düşün

    Müsahibədə olduğun kimi cavabı ucadan və ya içində söylə, sonra aç.

  5. Açıq sualMiddle

    Test double-ların hansı növləri var və state verification ilə behaviour verification arasında fərq nədir?

    Əvvəlcə özün düşün

    Müsahibədə olduğun kimi cavabı ucadan və ya içində söylə, sonra aç.

  6. Nəticəni təxmin etSenior

    Adi JS, Vitest yoxdur. lineTotal data mənbəyini parametr kimi alır. Unit test ona əllə yazılmış stub ötürür, production isə real client-i. fromStub === 36 yoxlaması expect(fromStub).toBe(36) əvəzinədir. Kod konsola nə çıxaracaq?

    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. Açıq sualSenior

    Pull request-də checkout() testi layihənin cart store-unu, pricing modulunu və API client-ini vi.mock ilə mock edir, onların qaytardığı dəyərləri stub edir və hər birinə yalnız toHaveBeenCalledWith yazır. Review-da nə deyərdin və testi necə yenidən yazardın?

    Əvvəlcə özün düşün

    Müsahibədə olduğun kimi cavabı ucadan və ya içində söylə, sonra aç.