Как проверить обработчик события прокрутки в Jest - PullRequest
0 голосов
/ 31 января 2020

Я вызываю $('.all-products-tab-buttons .row').scroll() метод в моем js файле. Но не могу узнать, как проверить этот метод, используя JEST.

Полный код приведен ниже:

$('.all-products-tab-buttons .row').scroll(event => {
     let $width = $('.all-products-tab-buttons .row').outerWidth();
     let $scrollWidth = $('.all-products-tab-buttons .row')[0].scrollWidth;
     let $scrollLeft = $('.all-products-tab-buttons .row').scrollLeft();
     if ($scrollWidth - $width === $scrollLeft) {
        $('.all-products-tab-buttons').addClass('remove');
     } else {
        $('.all-products-tab-buttons').removeClass('remove');
     }
});

Как я могу проверить, если и еще условия тоже?

1 Ответ

0 голосов
/ 03 февраля 2020

Вот решение для модульного теста:

index.js:

import $ from 'jquery';

function main() {
  $('.all-products-tab-buttons .row').scroll((event) => {
    let $width = $('.all-products-tab-buttons .row').outerWidth();
    let $scrollWidth = $('.all-products-tab-buttons .row')[0].scrollWidth;
    let $scrollLeft = $('.all-products-tab-buttons .row').scrollLeft();
    if ($scrollWidth - $width === $scrollLeft) {
      $('.all-products-tab-buttons').addClass('remove');
    } else {
      $('.all-products-tab-buttons').removeClass('remove');
    }
  });
}

export default main;

index.test.js:

import main from './';
import $ from 'jquery';

jest.mock('jquery', () => jest.fn());

describe('60003884', () => {
  it('should add class', () => {
    const tabButtonRows = [{ scrollWidth: 200 }];
    tabButtonRows.constructor.prototype.scroll = jest.fn().mockImplementationOnce((handler) => {
      handler();
    });
    tabButtonRows.constructor.prototype.outerWidth = jest.fn().mockReturnValueOnce(100);
    tabButtonRows.constructor.prototype.scrollLeft = jest.fn().mockReturnValueOnce(100);
    const tabButtons = { addClass: jest.fn(), removeClass: jest.fn() };

    $.mockImplementation((selector) => {
      switch (selector) {
        case '.all-products-tab-buttons .row':
          return tabButtonRows;
        case '.all-products-tab-buttons':
          return tabButtons;
      }
    });
    main();
    expect(tabButtons.addClass).toBeCalledWith('remove');
  });

  it('should remove class', () => {
    const tabButtonRows = [{ scrollWidth: 200 }];
    tabButtonRows.constructor.prototype.scroll = jest.fn().mockImplementationOnce((handler) => {
      handler();
    });
    tabButtonRows.constructor.prototype.outerWidth = jest.fn().mockReturnValueOnce(100);
    tabButtonRows.constructor.prototype.scrollLeft = jest.fn().mockReturnValueOnce(50);
    const tabButtons = { addClass: jest.fn(), removeClass: jest.fn() };

    $.mockImplementation((selector) => {
      switch (selector) {
        case '.all-products-tab-buttons .row':
          return tabButtonRows;
        case '.all-products-tab-buttons':
          return tabButtons;
      }
    });
    main();
    expect(tabButtons.removeClass).toBeCalledWith('remove');
  });
});

Результаты модульного теста со 100% покрытием:

 PASS  src/stackoverflow/60003884/index.test.js (14.309s)
  60003884
    ✓ should add class (7ms)
    ✓ should remove class (1ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 index.js |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        16.079s

Исходный код: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/60003884

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...