جاوااسکریپت - شبیهسازی ویژگی lang مربوط به documentElement در Jest


من در تلاش هستم تا خصوصیت lang عنصر documentElement را برای آزمایشهایم دستکاری کنم و نمیتوانم بفهمم چگونه میتوانم این کار را انجام دهم. من قبلاً تلاش کردهام setupFiles را در پیکربندی Jest تعریف کنم - و این به من امکان تعریف آن را داد اما هیچ گزینهای برای تغییر آن برای آزمایشهای مختلف وجود نداشت - همانطور که در اینجا توضیح داده شده است: Mocking `document` در jest

بخشی از تست کد شبیه به این است:

const lang: string = document.documentElement.lang ?
      document.documentElement.lang : Constraints.DEFAULT_LANGUAGE;

ظاهر تست اینگونه است:

   test('should pass `en` language when document hasn`t any specified', () => {
    const spy = jest.spyOn(window.document, 'documentElement', 'get');
    expect(spy).toHaveBeenCalled();
  });

و با setupFiles:

Object.defineProperty(document, 'documentElement', {
    writable: true,
    configurable: true,
    value: document.createElement('document')
});

زمانی که setupFiles دارم، خطا دریافت میکنم: Property documentElement does not have access type get

اما وقتی سعی میکنم بدون پیکربندی setupfile.js روی آن جاسوسی کنم، هیچوقت جاسوسی فراخوانی نمیشود.

ویرایش

مثال واضحتر از آنچه میخواهم به آن برسم:

    const lang: string = document.documentElement.lang ?
      document.documentElement.lang : Constraints.DEFAULT_LANGUAGE;
    component.src = `/${lang}/mysite`;
test('should pass `de` language when document has one specified', () => {
    const spy = jest.spyOn(window.document, 'documentElement', 'get');
    const mockElement = document.createElement('document');
    mockElement.lang = 'de';
    spy.mockReturnValue(mockElement);
    expect(component.src).toContain('/de/');
  });

و در تست من دریافت میکنم:

expect(received).toContain(expected) // indexOf

    Expected substring: "/de/"
    Received string:    "http://localhost/en/mysite"

پاسخ شماره ۱

خب، شما تقریباً به آنجا رسیدهاید، اما وقتی به ویژگی document.documentElement.lang دسترسی پیدا میکنید، متد get فعال شده است. بنابراین باید آن شیء را مانند زیر تعریف کنید؛

Object.defineProperty(document, 'documentElement', {
    configurable: true,
    get () {
        return document.createElement('document');
    },
});

و در آزمایشت؛

قبل از خط expect باید این خط را اضافه کنید تا getter فعال شود و spy فراخوانی شود.

window.document.documentElement.lang;

ویرایش

دربارهی موارد بالا فراموش کن.

به سادگی بلوک کد راهاندازی خود را حذف کنید، به نظر من نیازی به جاسوس یا چیزی مشابه ندارید.

یک متد برای تنظیم زبان در ثابت خود ایجاد کنید. سپس آن متد را تست کنید به جای اینکه عمل get از documentElement را تست کنید.

قبل از فراخوانی متد خود، از کد زیر برای تنظیم ویژگی زبان استفاده کنید. (تصور کنید متد زبان دارید)

test('should return `de` language when document has one specified', () => {
    Object.defineProperty(document.documentElement, 'lang', { value: 'de', configurable: true });

    expect(component.language()).toBe('de');
});