From 3ea39841c8049525e31e9f4d6300f0c60cdb42de Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Tue, 24 Jan 2023 13:33:51 +0100 Subject: Adding upstream version 5.2.3+dfsg. Signed-off-by: Daniel Baumann --- js/tests/README.md | 73 + js/tests/browsers.js | 79 + js/tests/helpers/fixture.js | 47 + js/tests/integration/bundle-modularity.js | 7 + js/tests/integration/bundle.js | 6 + js/tests/integration/index.html | 67 + js/tests/integration/rollup.bundle-modularity.js | 17 + js/tests/integration/rollup.bundle.js | 24 + js/tests/karma.conf.js | 171 ++ js/tests/unit/.eslintrc.json | 13 + js/tests/unit/alert.spec.js | 259 +++ js/tests/unit/base-component.spec.js | 168 ++ js/tests/unit/button.spec.js | 183 ++ js/tests/unit/carousel.spec.js | 1570 ++++++++++++++ js/tests/unit/collapse.spec.js | 1062 ++++++++++ js/tests/unit/dom/data.spec.js | 106 + js/tests/unit/dom/event-handler.spec.js | 480 +++++ js/tests/unit/dom/manipulator.spec.js | 135 ++ js/tests/unit/dom/selector-engine.spec.js | 236 +++ js/tests/unit/dropdown.spec.js | 2430 ++++++++++++++++++++++ js/tests/unit/jquery.spec.js | 60 + js/tests/unit/modal.spec.js | 1298 ++++++++++++ js/tests/unit/offcanvas.spec.js | 912 ++++++++ js/tests/unit/popover.spec.js | 413 ++++ js/tests/unit/scrollspy.spec.js | 946 +++++++++ js/tests/unit/tab.spec.js | 1101 ++++++++++ js/tests/unit/toast.spec.js | 670 ++++++ js/tests/unit/tooltip.spec.js | 1551 ++++++++++++++ js/tests/unit/util/backdrop.spec.js | 321 +++ js/tests/unit/util/component-functions.spec.js | 108 + js/tests/unit/util/config.spec.js | 166 ++ js/tests/unit/util/focustrap.spec.js | 218 ++ js/tests/unit/util/index.spec.js | 814 ++++++++ js/tests/unit/util/sanitizer.spec.js | 105 + js/tests/unit/util/scrollbar.spec.js | 363 ++++ js/tests/unit/util/swipe.spec.js | 291 +++ js/tests/unit/util/template-factory.spec.js | 306 +++ js/tests/visual/.eslintrc.json | 19 + js/tests/visual/alert.html | 48 + js/tests/visual/button.html | 49 + js/tests/visual/carousel.html | 65 + js/tests/visual/collapse.html | 76 + js/tests/visual/dropdown.html | 205 ++ js/tests/visual/modal.html | 275 +++ js/tests/visual/popover.html | 41 + js/tests/visual/scrollspy.html | 91 + js/tests/visual/tab.html | 223 ++ js/tests/visual/toast.html | 70 + js/tests/visual/tooltip.html | 138 ++ 49 files changed, 18076 insertions(+) create mode 100644 js/tests/README.md create mode 100644 js/tests/browsers.js create mode 100644 js/tests/helpers/fixture.js create mode 100644 js/tests/integration/bundle-modularity.js create mode 100644 js/tests/integration/bundle.js create mode 100644 js/tests/integration/index.html create mode 100644 js/tests/integration/rollup.bundle-modularity.js create mode 100644 js/tests/integration/rollup.bundle.js create mode 100644 js/tests/karma.conf.js create mode 100644 js/tests/unit/.eslintrc.json create mode 100644 js/tests/unit/alert.spec.js create mode 100644 js/tests/unit/base-component.spec.js create mode 100644 js/tests/unit/button.spec.js create mode 100644 js/tests/unit/carousel.spec.js create mode 100644 js/tests/unit/collapse.spec.js create mode 100644 js/tests/unit/dom/data.spec.js create mode 100644 js/tests/unit/dom/event-handler.spec.js create mode 100644 js/tests/unit/dom/manipulator.spec.js create mode 100644 js/tests/unit/dom/selector-engine.spec.js create mode 100644 js/tests/unit/dropdown.spec.js create mode 100644 js/tests/unit/jquery.spec.js create mode 100644 js/tests/unit/modal.spec.js create mode 100644 js/tests/unit/offcanvas.spec.js create mode 100644 js/tests/unit/popover.spec.js create mode 100644 js/tests/unit/scrollspy.spec.js create mode 100644 js/tests/unit/tab.spec.js create mode 100644 js/tests/unit/toast.spec.js create mode 100644 js/tests/unit/tooltip.spec.js create mode 100644 js/tests/unit/util/backdrop.spec.js create mode 100644 js/tests/unit/util/component-functions.spec.js create mode 100644 js/tests/unit/util/config.spec.js create mode 100644 js/tests/unit/util/focustrap.spec.js create mode 100644 js/tests/unit/util/index.spec.js create mode 100644 js/tests/unit/util/sanitizer.spec.js create mode 100644 js/tests/unit/util/scrollbar.spec.js create mode 100644 js/tests/unit/util/swipe.spec.js create mode 100644 js/tests/unit/util/template-factory.spec.js create mode 100644 js/tests/visual/.eslintrc.json create mode 100644 js/tests/visual/alert.html create mode 100644 js/tests/visual/button.html create mode 100644 js/tests/visual/carousel.html create mode 100644 js/tests/visual/collapse.html create mode 100644 js/tests/visual/dropdown.html create mode 100644 js/tests/visual/modal.html create mode 100644 js/tests/visual/popover.html create mode 100644 js/tests/visual/scrollspy.html create mode 100644 js/tests/visual/tab.html create mode 100644 js/tests/visual/toast.html create mode 100644 js/tests/visual/tooltip.html (limited to 'js/tests') diff --git a/js/tests/README.md b/js/tests/README.md new file mode 100644 index 0000000..79d05d4 --- /dev/null +++ b/js/tests/README.md @@ -0,0 +1,73 @@ +## How does Bootstrap's test suite work? + +Bootstrap uses [Jasmine](https://jasmine.github.io/). Each plugin has a file dedicated to its tests in `tests/unit/.spec.js`. + +- `visual/` contains "visual" tests which are run interactively in real browsers and require manual verification by humans. + +To run the unit test suite via [Karma](https://karma-runner.github.io/), run `npm run js-test`. +To run the unit test suite via [Karma](https://karma-runner.github.io/) and debug, run `npm run js-debug`. + +## How do I add a new unit test? + +1. Locate and open the file dedicated to the plugin which you need to add tests to (`tests/unit/.spec.js`). +2. Review the [Jasmine API Documentation](https://jasmine.github.io/pages/docs_home.html) and use the existing tests as references for how to structure your new tests. +3. Write the necessary unit test(s) for the new or revised functionality. +4. Run `npm run js-test` to see the results of your newly-added test(s). + +**Note:** Your new unit tests should fail before your changes are applied to the plugin, and should pass after your changes are applied to the plugin. + +## What should a unit test look like? + +- Each test should have a unique name clearly stating what unit is being tested. +- Each test should be in the corresponding `describe`. +- Each test should test only one unit per test, although one test can include several assertions. Create multiple tests for multiple units of functionality. +- Each test should use [`expect`](https://jasmine.github.io/api/edge/matchers.html) to ensure something is expected. +- Each test should follow the project's [JavaScript Code Guidelines](https://github.com/twbs/bootstrap/blob/main/.github/CONTRIBUTING.md#js) + +## Code coverage + +Currently we're aiming for at least 90% test coverage for our code. To ensure your changes meet or exceed this limit, run `npm run js-test-karma` and open the file in `js/coverage/lcov-report/index.html` to see the code coverage for each plugin. See more details when you select a plugin and ensure your change is fully covered by unit tests. + +### Example tests + +```js +// Synchronous test +describe('getInstance', () => { + it('should return null if there is no instance', () => { + // Make assertion + expect(Tab.getInstance(fixtureEl)).toBeNull() + }) + + it('should return this instance', () => { + fixtureEl.innerHTML = '
' + + const divEl = fixtureEl.querySelector('div') + const tab = new Tab(divEl) + + // Make assertion + expect(Tab.getInstance(divEl)).toEqual(tab) + }) +}) + +// Asynchronous test +it('should show a tooltip without the animation', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl, { + animation: false + }) + + tooltipEl.addEventListener('shown.bs.tooltip', () => { + const tip = document.querySelector('.tooltip') + + expect(tip).not.toBeNull() + expect(tip.classList.contains('fade')).toEqual(false) + resolve() + }) + + tooltip.show() + }) +}) +``` diff --git a/js/tests/browsers.js b/js/tests/browsers.js new file mode 100644 index 0000000..8adedc6 --- /dev/null +++ b/js/tests/browsers.js @@ -0,0 +1,79 @@ +/* eslint-env node */ +/* eslint-disable camelcase */ + +const browsers = { + safariMac: { + base: 'BrowserStack', + os: 'OS X', + os_version: 'Catalina', + browser: 'Safari', + browser_version: 'latest' + }, + chromeMac: { + base: 'BrowserStack', + os: 'OS X', + os_version: 'Catalina', + browser: 'Chrome', + browser_version: 'latest' + }, + firefoxMac: { + base: 'BrowserStack', + os: 'OS X', + os_version: 'Catalina', + browser: 'Firefox', + browser_version: 'latest' + }, + chromeWin10: { + base: 'BrowserStack', + os: 'Windows', + os_version: '10', + browser: 'Chrome', + browser_version: '60' + }, + firefoxWin10: { + base: 'BrowserStack', + os: 'Windows', + os_version: '10', + browser: 'Firefox', + browser_version: '60' + }, + chromeWin10Latest: { + base: 'BrowserStack', + os: 'Windows', + os_version: '10', + browser: 'Chrome', + browser_version: 'latest' + }, + firefoxWin10Latest: { + base: 'BrowserStack', + os: 'Windows', + os_version: '10', + browser: 'Firefox', + browser_version: 'latest' + }, + iphone7: { + base: 'BrowserStack', + os: 'ios', + os_version: '12.0', + device: 'iPhone 7', + real_mobile: true + }, + iphone12: { + base: 'BrowserStack', + os: 'ios', + os_version: '14.0', + device: 'iPhone 12', + real_mobile: true + }, + pixel2: { + base: 'BrowserStack', + os: 'android', + os_version: '8.0', + device: 'Google Pixel 2', + real_mobile: true + } +} + +module.exports = { + browsers +} diff --git a/js/tests/helpers/fixture.js b/js/tests/helpers/fixture.js new file mode 100644 index 0000000..5ad14e1 --- /dev/null +++ b/js/tests/helpers/fixture.js @@ -0,0 +1,47 @@ +const fixtureId = 'fixture' + +export const getFixture = () => { + let fixtureElement = document.getElementById(fixtureId) + + if (!fixtureElement) { + fixtureElement = document.createElement('div') + fixtureElement.setAttribute('id', fixtureId) + fixtureElement.style.position = 'absolute' + fixtureElement.style.top = '-10000px' + fixtureElement.style.left = '-10000px' + fixtureElement.style.width = '10000px' + fixtureElement.style.height = '10000px' + document.body.append(fixtureElement) + } + + return fixtureElement +} + +export const clearFixture = () => { + const fixtureElement = getFixture() + + fixtureElement.innerHTML = '' +} + +export const createEvent = (eventName, parameters = {}) => { + return new Event(eventName, parameters) +} + +export const jQueryMock = { + elements: undefined, + fn: {}, + each(fn) { + for (const element of this.elements) { + fn.call(element) + } + } +} + +export const clearBodyAndDocument = () => { + const attributes = ['data-bs-padding-right', 'style'] + + for (const attribute of attributes) { + document.documentElement.removeAttribute(attribute) + document.body.removeAttribute(attribute) + } +} diff --git a/js/tests/integration/bundle-modularity.js b/js/tests/integration/bundle-modularity.js new file mode 100644 index 0000000..8546141 --- /dev/null +++ b/js/tests/integration/bundle-modularity.js @@ -0,0 +1,7 @@ +import Tooltip from '../../dist/tooltip' +import '../../dist/carousel' + +window.addEventListener('load', () => { + [].concat(...document.querySelectorAll('[data-bs-toggle="tooltip"]')) + .map(tooltipNode => new Tooltip(tooltipNode)) +}) diff --git a/js/tests/integration/bundle.js b/js/tests/integration/bundle.js new file mode 100644 index 0000000..452088a --- /dev/null +++ b/js/tests/integration/bundle.js @@ -0,0 +1,6 @@ +import { Tooltip } from '../../../dist/js/bootstrap.esm.js' + +window.addEventListener('load', () => { + [].concat(...document.querySelectorAll('[data-bs-toggle="tooltip"]')) + .map(tooltipNode => new Tooltip(tooltipNode)) +}) diff --git a/js/tests/integration/index.html b/js/tests/integration/index.html new file mode 100644 index 0000000..4c71bad --- /dev/null +++ b/js/tests/integration/index.html @@ -0,0 +1,67 @@ + + + + + + + + + + + Hello, world! + + +
+

Hello, world!

+ +
+ + + +
+
+ + + + diff --git a/js/tests/integration/rollup.bundle-modularity.js b/js/tests/integration/rollup.bundle-modularity.js new file mode 100644 index 0000000..a8670ca --- /dev/null +++ b/js/tests/integration/rollup.bundle-modularity.js @@ -0,0 +1,17 @@ +/* eslint-env node */ + +const commonjs = require('@rollup/plugin-commonjs') +const configRollup = require('./rollup.bundle') + +const config = { + ...configRollup, + input: 'js/tests/integration/bundle-modularity.js', + output: { + file: 'js/coverage/bundle-modularity.js', + format: 'iife' + } +} + +config.plugins.unshift(commonjs()) + +module.exports = config diff --git a/js/tests/integration/rollup.bundle.js b/js/tests/integration/rollup.bundle.js new file mode 100644 index 0000000..caddcab --- /dev/null +++ b/js/tests/integration/rollup.bundle.js @@ -0,0 +1,24 @@ +/* eslint-env node */ + +const { babel } = require('@rollup/plugin-babel') +const { nodeResolve } = require('@rollup/plugin-node-resolve') +const replace = require('@rollup/plugin-replace') + +module.exports = { + input: 'js/tests/integration/bundle.js', + output: { + file: 'js/coverage/bundle.js', + format: 'iife' + }, + plugins: [ + replace({ + 'process.env.NODE_ENV': '"production"', + preventAssignment: true + }), + nodeResolve(), + babel({ + exclude: 'node_modules/**', + babelHelpers: 'bundled' + }) + ] +} diff --git a/js/tests/karma.conf.js b/js/tests/karma.conf.js new file mode 100644 index 0000000..6636ff1 --- /dev/null +++ b/js/tests/karma.conf.js @@ -0,0 +1,171 @@ +/* eslint-env node */ + +'use strict' + +const path = require('node:path') +const ip = require('ip') +const { babel } = require('@rollup/plugin-babel') +const istanbul = require('rollup-plugin-istanbul') +const { nodeResolve } = require('@rollup/plugin-node-resolve') +const replace = require('@rollup/plugin-replace') +const { browsers } = require('./browsers') + +const ENV = process.env +const BROWSERSTACK = Boolean(ENV.BROWSERSTACK) +const DEBUG = Boolean(ENV.DEBUG) +const JQUERY_TEST = Boolean(ENV.JQUERY) + +const frameworks = [ + 'jasmine' +] + +const plugins = [ + 'karma-jasmine', + 'karma-rollup-preprocessor' +] + +const reporters = ['dots'] + +const detectBrowsers = { + usePhantomJS: false, + postDetection(availableBrowser) { + // On CI just use Chrome + if (ENV.CI === true) { + return ['ChromeHeadless'] + } + + if (availableBrowser.includes('Chrome')) { + return DEBUG ? ['Chrome'] : ['ChromeHeadless'] + } + + if (availableBrowser.includes('Chromium')) { + return DEBUG ? ['Chromium'] : ['ChromiumHeadless'] + } + + if (availableBrowser.includes('Firefox')) { + return DEBUG ? ['Firefox'] : ['FirefoxHeadless'] + } + + throw new Error('Please install Chrome, Chromium or Firefox') + } +} + +const config = { + basePath: '../..', + port: 9876, + colors: true, + autoWatch: false, + singleRun: true, + concurrency: Number.POSITIVE_INFINITY, + client: { + clearContext: false + }, + files: [ + 'node_modules/hammer-simulator/index.js', + { + pattern: 'js/tests/unit/**/!(jquery).spec.js', + watched: !BROWSERSTACK + } + ], + preprocessors: { + 'js/tests/unit/**/*.spec.js': ['rollup'] + }, + rollupPreprocessor: { + plugins: [ + replace({ + 'process.env.NODE_ENV': '"dev"', + preventAssignment: true + }), + istanbul({ + exclude: [ + 'node_modules/**', + 'js/tests/unit/**/*.spec.js', + 'js/tests/helpers/**/*.js' + ] + }), + babel({ + // Only transpile our source code + exclude: 'node_modules/**', + // Inline the required helpers in each file + babelHelpers: 'inline' + }), + nodeResolve() + ], + output: { + format: 'iife', + name: 'bootstrapTest', + sourcemap: 'inline', + generatedCode: 'es2015' + } + } +} + +if (BROWSERSTACK) { + config.hostname = ip.address() + config.browserStack = { + username: ENV.BROWSER_STACK_USERNAME, + accessKey: ENV.BROWSER_STACK_ACCESS_KEY, + build: `bootstrap-${ENV.GITHUB_SHA ? ENV.GITHUB_SHA.slice(0, 7) + '-' : ''}${new Date().toISOString()}`, + project: 'Bootstrap', + retryLimit: 2 + } + plugins.push('karma-browserstack-launcher', 'karma-jasmine-html-reporter') + config.customLaunchers = browsers + config.browsers = Object.keys(browsers) + reporters.push('BrowserStack', 'kjhtml') +} else if (JQUERY_TEST) { + frameworks.push('detectBrowsers') + plugins.push( + 'karma-chrome-launcher', + 'karma-firefox-launcher', + 'karma-detect-browsers' + ) + config.detectBrowsers = detectBrowsers + config.files = [ + 'node_modules/jquery/dist/jquery.slim.min.js', + { + pattern: 'js/tests/unit/jquery.spec.js', + watched: false + } + ] +} else { + frameworks.push('detectBrowsers') + plugins.push( + 'karma-chrome-launcher', + 'karma-firefox-launcher', + 'karma-detect-browsers', + 'karma-coverage-istanbul-reporter' + ) + reporters.push('coverage-istanbul') + config.detectBrowsers = detectBrowsers + config.coverageIstanbulReporter = { + dir: path.resolve(__dirname, '../coverage/'), + reports: ['lcov', 'text-summary'], + thresholds: { + emitWarning: false, + global: { + statements: 90, + branches: 89, + functions: 90, + lines: 90 + } + } + } + + if (DEBUG) { + config.hostname = ip.address() + plugins.push('karma-jasmine-html-reporter') + reporters.push('kjhtml') + config.singleRun = false + config.autoWatch = true + } +} + +config.frameworks = frameworks +config.plugins = plugins +config.reporters = reporters + +module.exports = karmaConfig => { + config.logLevel = karmaConfig.LOG_ERROR + karmaConfig.set(config) +} diff --git a/js/tests/unit/.eslintrc.json b/js/tests/unit/.eslintrc.json new file mode 100644 index 0000000..6362a1a --- /dev/null +++ b/js/tests/unit/.eslintrc.json @@ -0,0 +1,13 @@ +{ + "extends": [ + "../../../.eslintrc.json" + ], + "env": { + "jasmine": true + }, + "rules": { + "unicorn/consistent-function-scoping": "off", + "unicorn/no-useless-undefined": "off", + "unicorn/prefer-add-event-listener": "off" + } +} diff --git a/js/tests/unit/alert.spec.js b/js/tests/unit/alert.spec.js new file mode 100644 index 0000000..d3740c9 --- /dev/null +++ b/js/tests/unit/alert.spec.js @@ -0,0 +1,259 @@ +import Alert from '../../src/alert' +import { getTransitionDurationFromElement } from '../../src/util/index' +import { clearFixture, getFixture, jQueryMock } from '../helpers/fixture' + +describe('Alert', () => { + let fixtureEl + + beforeAll(() => { + fixtureEl = getFixture() + }) + + afterEach(() => { + clearFixture() + }) + + it('should take care of element either passed as a CSS selector or DOM element', () => { + fixtureEl.innerHTML = '
' + + const alertEl = fixtureEl.querySelector('.alert') + const alertBySelector = new Alert('.alert') + const alertByElement = new Alert(alertEl) + + expect(alertBySelector._element).toEqual(alertEl) + expect(alertByElement._element).toEqual(alertEl) + }) + + it('should return version', () => { + expect(Alert.VERSION).toEqual(jasmine.any(String)) + }) + + describe('DATA_KEY', () => { + it('should return plugin data key', () => { + expect(Alert.DATA_KEY).toEqual('bs.alert') + }) + }) + + describe('data-api', () => { + it('should close an alert without instantiating it manually', () => { + fixtureEl.innerHTML = [ + '
', + ' ', + '
' + ].join('') + + const button = document.querySelector('button') + + button.click() + expect(document.querySelectorAll('.alert')).toHaveSize(0) + }) + + it('should close an alert without instantiating it manually with the parent selector', () => { + fixtureEl.innerHTML = [ + '
', + ' ', + '
' + ].join('') + + const button = document.querySelector('button') + + button.click() + expect(document.querySelectorAll('.alert')).toHaveSize(0) + }) + }) + + describe('close', () => { + it('should close an alert', () => { + return new Promise(resolve => { + const spy = jasmine.createSpy('spy', getTransitionDurationFromElement) + fixtureEl.innerHTML = '
' + + const alertEl = document.querySelector('.alert') + const alert = new Alert(alertEl) + + alertEl.addEventListener('closed.bs.alert', () => { + expect(document.querySelectorAll('.alert')).toHaveSize(0) + expect(spy).not.toHaveBeenCalled() + resolve() + }) + + alert.close() + }) + }) + + it('should close alert with fade class', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + + const alertEl = document.querySelector('.alert') + const alert = new Alert(alertEl) + + alertEl.addEventListener('transitionend', () => { + expect().nothing() + }) + + alertEl.addEventListener('closed.bs.alert', () => { + expect(document.querySelectorAll('.alert')).toHaveSize(0) + resolve() + }) + + alert.close() + }) + }) + + it('should not remove alert if close event is prevented', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = '
' + + const getAlert = () => document.querySelector('.alert') + const alertEl = getAlert() + const alert = new Alert(alertEl) + + alertEl.addEventListener('close.bs.alert', event => { + event.preventDefault() + setTimeout(() => { + expect(getAlert()).not.toBeNull() + resolve() + }, 10) + }) + + alertEl.addEventListener('closed.bs.alert', () => { + reject(new Error('should not fire closed event')) + }) + + alert.close() + }) + }) + }) + + describe('dispose', () => { + it('should dispose an alert', () => { + fixtureEl.innerHTML = '
' + + const alertEl = document.querySelector('.alert') + const alert = new Alert(alertEl) + + expect(Alert.getInstance(alertEl)).not.toBeNull() + + alert.dispose() + + expect(Alert.getInstance(alertEl)).toBeNull() + }) + }) + + describe('jQueryInterface', () => { + it('should handle config passed and toggle existing alert', () => { + fixtureEl.innerHTML = '
' + + const alertEl = fixtureEl.querySelector('.alert') + const alert = new Alert(alertEl) + + const spy = spyOn(alert, 'close') + + jQueryMock.fn.alert = Alert.jQueryInterface + jQueryMock.elements = [alertEl] + + jQueryMock.fn.alert.call(jQueryMock, 'close') + + expect(spy).toHaveBeenCalled() + }) + + it('should create new alert instance and call close', () => { + fixtureEl.innerHTML = '
' + + const alertEl = fixtureEl.querySelector('.alert') + + jQueryMock.fn.alert = Alert.jQueryInterface + jQueryMock.elements = [alertEl] + + expect(Alert.getInstance(alertEl)).toBeNull() + jQueryMock.fn.alert.call(jQueryMock, 'close') + + expect(fixtureEl.querySelector('.alert')).toBeNull() + }) + + it('should just create an alert instance without calling close', () => { + fixtureEl.innerHTML = '
' + + const alertEl = fixtureEl.querySelector('.alert') + + jQueryMock.fn.alert = Alert.jQueryInterface + jQueryMock.elements = [alertEl] + + jQueryMock.fn.alert.call(jQueryMock) + + expect(Alert.getInstance(alertEl)).not.toBeNull() + expect(fixtureEl.querySelector('.alert')).not.toBeNull() + }) + + it('should throw an error on undefined method', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const action = 'undefinedMethod' + + jQueryMock.fn.alert = Alert.jQueryInterface + jQueryMock.elements = [div] + + expect(() => { + jQueryMock.fn.alert.call(jQueryMock, action) + }).toThrowError(TypeError, `No method named "${action}"`) + }) + + it('should throw an error on protected method', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const action = '_getConfig' + + jQueryMock.fn.alert = Alert.jQueryInterface + jQueryMock.elements = [div] + + expect(() => { + jQueryMock.fn.alert.call(jQueryMock, action) + }).toThrowError(TypeError, `No method named "${action}"`) + }) + }) + + describe('getInstance', () => { + it('should return alert instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const alert = new Alert(div) + + expect(Alert.getInstance(div)).toEqual(alert) + expect(Alert.getInstance(div)).toBeInstanceOf(Alert) + }) + + it('should return null when there is no alert instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(Alert.getInstance(div)).toBeNull() + }) + }) + + describe('getOrCreateInstance', () => { + it('should return alert instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const alert = new Alert(div) + + expect(Alert.getOrCreateInstance(div)).toEqual(alert) + expect(Alert.getInstance(div)).toEqual(Alert.getOrCreateInstance(div, {})) + expect(Alert.getOrCreateInstance(div)).toBeInstanceOf(Alert) + }) + + it('should return new instance when there is no alert instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(Alert.getInstance(div)).toBeNull() + expect(Alert.getOrCreateInstance(div)).toBeInstanceOf(Alert) + }) + }) +}) diff --git a/js/tests/unit/base-component.spec.js b/js/tests/unit/base-component.spec.js new file mode 100644 index 0000000..b2352d6 --- /dev/null +++ b/js/tests/unit/base-component.spec.js @@ -0,0 +1,168 @@ +import BaseComponent from '../../src/base-component' +import { clearFixture, getFixture } from '../helpers/fixture' +import EventHandler from '../../src/dom/event-handler' +import { noop } from '../../src/util' + +class DummyClass extends BaseComponent { + constructor(element) { + super(element) + + EventHandler.on(this._element, `click${DummyClass.EVENT_KEY}`, noop) + } + + static get NAME() { + return 'dummy' + } +} + +describe('Base Component', () => { + let fixtureEl + const name = 'dummy' + let element + let instance + const createInstance = () => { + fixtureEl.innerHTML = '
' + element = fixtureEl.querySelector('#foo') + instance = new DummyClass(element) + } + + beforeAll(() => { + fixtureEl = getFixture() + }) + + afterEach(() => { + clearFixture() + }) + + describe('Static Methods', () => { + describe('VERSION', () => { + it('should return version', () => { + expect(DummyClass.VERSION).toEqual(jasmine.any(String)) + }) + }) + + describe('DATA_KEY', () => { + it('should return plugin data key', () => { + expect(DummyClass.DATA_KEY).toEqual(`bs.${name}`) + }) + }) + + describe('NAME', () => { + it('should throw an Error if it is not initialized', () => { + expect(() => { + // eslint-disable-next-line no-unused-expressions + BaseComponent.NAME + }).toThrowError(Error) + }) + + it('should return plugin NAME', () => { + expect(DummyClass.NAME).toEqual(name) + }) + }) + + describe('EVENT_KEY', () => { + it('should return plugin event key', () => { + expect(DummyClass.EVENT_KEY).toEqual(`.bs.${name}`) + }) + }) + }) + + describe('Public Methods', () => { + describe('constructor', () => { + it('should accept element, either passed as a CSS selector or DOM element', () => { + fixtureEl.innerHTML = [ + '
', + '
' + ].join('') + + const el = fixtureEl.querySelector('#foo') + const elInstance = new DummyClass(el) + const selectorInstance = new DummyClass('#bar') + + expect(elInstance._element).toEqual(el) + expect(selectorInstance._element).toEqual(fixtureEl.querySelector('#bar')) + }) + + it('should not initialize and add element record to Data (caching), if argument `element` is not an HTML element', () => { + fixtureEl.innerHTML = '' + + const el = fixtureEl.querySelector('#foo') + const elInstance = new DummyClass(el) + const selectorInstance = new DummyClass('#bar') + + expect(elInstance._element).not.toBeDefined() + expect(selectorInstance._element).not.toBeDefined() + }) + }) + + describe('dispose', () => { + it('should dispose an component', () => { + createInstance() + expect(DummyClass.getInstance(element)).not.toBeNull() + + instance.dispose() + + expect(DummyClass.getInstance(element)).toBeNull() + expect(instance._element).toBeNull() + }) + + it('should de-register element event listeners', () => { + createInstance() + const spy = spyOn(EventHandler, 'off') + + instance.dispose() + + expect(spy).toHaveBeenCalledWith(element, DummyClass.EVENT_KEY) + }) + }) + + describe('getInstance', () => { + it('should return an instance', () => { + createInstance() + + expect(DummyClass.getInstance(element)).toEqual(instance) + expect(DummyClass.getInstance(element)).toBeInstanceOf(DummyClass) + }) + + it('should accept element, either passed as a CSS selector, jQuery element, or DOM element', () => { + createInstance() + + expect(DummyClass.getInstance('#foo')).toEqual(instance) + expect(DummyClass.getInstance(element)).toEqual(instance) + + const fakejQueryObject = { + 0: element, + jquery: 'foo' + } + + expect(DummyClass.getInstance(fakejQueryObject)).toEqual(instance) + }) + + it('should return null when there is no instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(DummyClass.getInstance(div)).toBeNull() + }) + }) + + describe('getOrCreateInstance', () => { + it('should return an instance', () => { + createInstance() + + expect(DummyClass.getOrCreateInstance(element)).toEqual(instance) + expect(DummyClass.getInstance(element)).toEqual(DummyClass.getOrCreateInstance(element, {})) + expect(DummyClass.getOrCreateInstance(element)).toBeInstanceOf(DummyClass) + }) + + it('should return new instance when there is no alert instance', () => { + fixtureEl.innerHTML = '
' + element = fixtureEl.querySelector('#foo') + + expect(DummyClass.getInstance(element)).toBeNull() + expect(DummyClass.getOrCreateInstance(element)).toBeInstanceOf(DummyClass) + }) + }) + }) +}) diff --git a/js/tests/unit/button.spec.js b/js/tests/unit/button.spec.js new file mode 100644 index 0000000..09ed17e --- /dev/null +++ b/js/tests/unit/button.spec.js @@ -0,0 +1,183 @@ +import Button from '../../src/button' +import { getFixture, clearFixture, jQueryMock } from '../helpers/fixture' + +describe('Button', () => { + let fixtureEl + + beforeAll(() => { + fixtureEl = getFixture() + }) + + afterEach(() => { + clearFixture() + }) + + it('should take care of element either passed as a CSS selector or DOM element', () => { + fixtureEl.innerHTML = '' + const buttonEl = fixtureEl.querySelector('[data-bs-toggle="button"]') + const buttonBySelector = new Button('[data-bs-toggle="button"]') + const buttonByElement = new Button(buttonEl) + + expect(buttonBySelector._element).toEqual(buttonEl) + expect(buttonByElement._element).toEqual(buttonEl) + }) + + describe('VERSION', () => { + it('should return plugin version', () => { + expect(Button.VERSION).toEqual(jasmine.any(String)) + }) + }) + + describe('DATA_KEY', () => { + it('should return plugin data key', () => { + expect(Button.DATA_KEY).toEqual('bs.button') + }) + }) + + describe('data-api', () => { + it('should toggle active class on click', () => { + fixtureEl.innerHTML = [ + '', + '' + ].join('') + + const btn = fixtureEl.querySelector('.btn') + const divTest = fixtureEl.querySelector('.test') + const btnTestParent = fixtureEl.querySelector('.testParent') + + expect(btn).not.toHaveClass('active') + + btn.click() + + expect(btn).toHaveClass('active') + + btn.click() + + expect(btn).not.toHaveClass('active') + + divTest.click() + + expect(btnTestParent).toHaveClass('active') + }) + }) + + describe('toggle', () => { + it('should toggle aria-pressed', () => { + fixtureEl.innerHTML = '' + + const btnEl = fixtureEl.querySelector('.btn') + const button = new Button(btnEl) + + expect(btnEl.getAttribute('aria-pressed')).toEqual('false') + expect(btnEl).not.toHaveClass('active') + + button.toggle() + + expect(btnEl.getAttribute('aria-pressed')).toEqual('true') + expect(btnEl).toHaveClass('active') + }) + }) + + describe('dispose', () => { + it('should dispose a button', () => { + fixtureEl.innerHTML = '' + + const btnEl = fixtureEl.querySelector('.btn') + const button = new Button(btnEl) + + expect(Button.getInstance(btnEl)).not.toBeNull() + + button.dispose() + + expect(Button.getInstance(btnEl)).toBeNull() + }) + }) + + describe('jQueryInterface', () => { + it('should handle config passed and toggle existing button', () => { + fixtureEl.innerHTML = '' + + const btnEl = fixtureEl.querySelector('.btn') + const button = new Button(btnEl) + + const spy = spyOn(button, 'toggle') + + jQueryMock.fn.button = Button.jQueryInterface + jQueryMock.elements = [btnEl] + + jQueryMock.fn.button.call(jQueryMock, 'toggle') + + expect(spy).toHaveBeenCalled() + }) + + it('should create new button instance and call toggle', () => { + fixtureEl.innerHTML = '' + + const btnEl = fixtureEl.querySelector('.btn') + + jQueryMock.fn.button = Button.jQueryInterface + jQueryMock.elements = [btnEl] + + jQueryMock.fn.button.call(jQueryMock, 'toggle') + + expect(Button.getInstance(btnEl)).not.toBeNull() + expect(btnEl).toHaveClass('active') + }) + + it('should just create a button instance without calling toggle', () => { + fixtureEl.innerHTML = '' + + const btnEl = fixtureEl.querySelector('.btn') + + jQueryMock.fn.button = Button.jQueryInterface + jQueryMock.elements = [btnEl] + + jQueryMock.fn.button.call(jQueryMock) + + expect(Button.getInstance(btnEl)).not.toBeNull() + expect(btnEl).not.toHaveClass('active') + }) + }) + + describe('getInstance', () => { + it('should return button instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const button = new Button(div) + + expect(Button.getInstance(div)).toEqual(button) + expect(Button.getInstance(div)).toBeInstanceOf(Button) + }) + + it('should return null when there is no button instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(Button.getInstance(div)).toBeNull() + }) + }) + + describe('getOrCreateInstance', () => { + it('should return button instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const button = new Button(div) + + expect(Button.getOrCreateInstance(div)).toEqual(button) + expect(Button.getInstance(div)).toEqual(Button.getOrCreateInstance(div, {})) + expect(Button.getOrCreateInstance(div)).toBeInstanceOf(Button) + }) + + it('should return new instance when there is no button instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(Button.getInstance(div)).toBeNull() + expect(Button.getOrCreateInstance(div)).toBeInstanceOf(Button) + }) + }) +}) diff --git a/js/tests/unit/carousel.spec.js b/js/tests/unit/carousel.spec.js new file mode 100644 index 0000000..d951bd5 --- /dev/null +++ b/js/tests/unit/carousel.spec.js @@ -0,0 +1,1570 @@ +import Carousel from '../../src/carousel' +import EventHandler from '../../src/dom/event-handler' +import { clearFixture, createEvent, getFixture, jQueryMock } from '../helpers/fixture' +import { isRTL, noop } from '../../src/util/index' +import Swipe from '../../src/util/swipe' + +describe('Carousel', () => { + const { Simulator, PointerEvent } = window + const originWinPointerEvent = PointerEvent + const supportPointerEvent = Boolean(PointerEvent) + + const cssStyleCarousel = '.carousel.pointer-event { touch-action: none; }' + + const stylesCarousel = document.createElement('style') + stylesCarousel.type = 'text/css' + stylesCarousel.append(document.createTextNode(cssStyleCarousel)) + + const clearPointerEvents = () => { + window.PointerEvent = null + } + + const restorePointerEvents = () => { + window.PointerEvent = originWinPointerEvent + } + + let fixtureEl + + beforeAll(() => { + fixtureEl = getFixture() + }) + + afterEach(() => { + clearFixture() + }) + + describe('VERSION', () => { + it('should return plugin version', () => { + expect(Carousel.VERSION).toEqual(jasmine.any(String)) + }) + }) + + describe('Default', () => { + it('should return plugin default config', () => { + expect(Carousel.Default).toEqual(jasmine.any(Object)) + }) + }) + + describe('DATA_KEY', () => { + it('should return plugin data key', () => { + expect(Carousel.DATA_KEY).toEqual('bs.carousel') + }) + }) + + describe('constructor', () => { + it('should take care of element either passed as a CSS selector or DOM element', () => { + fixtureEl.innerHTML = '' + + const carouselEl = fixtureEl.querySelector('#myCarousel') + const carouselBySelector = new Carousel('#myCarousel') + const carouselByElement = new Carousel(carouselEl) + + expect(carouselBySelector._element).toEqual(carouselEl) + expect(carouselByElement._element).toEqual(carouselEl) + }) + + it('should start cycling if `ride`===`carousel`', () => { + fixtureEl.innerHTML = '' + + const carousel = new Carousel('#myCarousel') + expect(carousel._interval).not.toBeNull() + }) + + it('should not start cycling if `ride`!==`carousel`', () => { + fixtureEl.innerHTML = '' + + const carousel = new Carousel('#myCarousel') + expect(carousel._interval).toBeNull() + }) + + it('should go to next item if right arrow key is pressed', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const carouselEl = fixtureEl.querySelector('#myCarousel') + const carousel = new Carousel(carouselEl, { + keyboard: true + }) + + const spy = spyOn(carousel, '_keydown').and.callThrough() + + carouselEl.addEventListener('slid.bs.carousel', () => { + expect(fixtureEl.querySelector('.active')).toEqual(fixtureEl.querySelector('#item2')) + expect(spy).toHaveBeenCalled() + resolve() + }) + + const keydown = createEvent('keydown') + keydown.key = 'ArrowRight' + + carouselEl.dispatchEvent(keydown) + }) + }) + + it('should ignore keyboard events if data-bs-keyboard=false', () => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const spy = spyOn(EventHandler, 'trigger').and.callThrough() + const carouselEl = fixtureEl.querySelector('#myCarousel') + // eslint-disable-next-line no-new + new Carousel('#myCarousel') + expect(spy).not.toHaveBeenCalledWith(carouselEl, 'keydown.bs.carousel', jasmine.any(Function)) + }) + + it('should ignore mouse events if data-bs-pause=false', () => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const spy = spyOn(EventHandler, 'trigger').and.callThrough() + const carouselEl = fixtureEl.querySelector('#myCarousel') + // eslint-disable-next-line no-new + new Carousel('#myCarousel') + expect(spy).not.toHaveBeenCalledWith(carouselEl, 'hover.bs.carousel', jasmine.any(Function)) + }) + + it('should go to previous item if left arrow key is pressed', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const carouselEl = fixtureEl.querySelector('#myCarousel') + const carousel = new Carousel(carouselEl, { + keyboard: true + }) + + const spy = spyOn(carousel, '_keydown').and.callThrough() + + carouselEl.addEventListener('slid.bs.carousel', () => { + expect(fixtureEl.querySelector('.active')).toEqual(fixtureEl.querySelector('#item1')) + expect(spy).toHaveBeenCalled() + resolve() + }) + + const keydown = createEvent('keydown') + keydown.key = 'ArrowLeft' + + carouselEl.dispatchEvent(keydown) + }) + }) + + it('should not prevent keydown if key is not ARROW_LEFT or ARROW_RIGHT', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const carouselEl = fixtureEl.querySelector('#myCarousel') + const carousel = new Carousel(carouselEl, { + keyboard: true + }) + + const spy = spyOn(carousel, '_keydown').and.callThrough() + + carouselEl.addEventListener('keydown', event => { + expect(spy).toHaveBeenCalled() + expect(event.defaultPrevented).toBeFalse() + resolve() + }) + + const keydown = createEvent('keydown') + keydown.key = 'ArrowDown' + + carouselEl.dispatchEvent(keydown) + }) + }) + + it('should ignore keyboard events within s and ', + ' ', + ' ', + ' ', + ' ', + '' + ].join('') + + const carouselEl = fixtureEl.querySelector('#myCarousel') + const input = fixtureEl.querySelector('input') + const textarea = fixtureEl.querySelector('textarea') + const carousel = new Carousel(carouselEl, { + keyboard: true + }) + + const spyKeydown = spyOn(carousel, '_keydown').and.callThrough() + const spySlide = spyOn(carousel, '_slide') + + const keydown = createEvent('keydown', { bubbles: true, cancelable: true }) + keydown.key = 'ArrowRight' + Object.defineProperty(keydown, 'target', { + value: input, + writable: true, + configurable: true + }) + + input.dispatchEvent(keydown) + + expect(spyKeydown).toHaveBeenCalled() + expect(spySlide).not.toHaveBeenCalled() + + spyKeydown.calls.reset() + spySlide.calls.reset() + + Object.defineProperty(keydown, 'target', { + value: textarea + }) + textarea.dispatchEvent(keydown) + + expect(spyKeydown).toHaveBeenCalled() + expect(spySlide).not.toHaveBeenCalled() + }) + + it('should not slide if arrow key is pressed and carousel is sliding', () => { + fixtureEl.innerHTML = '
' + + const carouselEl = fixtureEl.querySelector('div') + const carousel = new Carousel(carouselEl, {}) + + const spy = spyOn(EventHandler, 'trigger') + + carousel._isSliding = true + + for (const key of ['ArrowLeft', 'ArrowRight']) { + const keydown = createEvent('keydown') + keydown.key = key + + carouselEl.dispatchEvent(keydown) + } + + expect(spy).not.toHaveBeenCalled() + }) + + it('should wrap around from end to start when wrap option is true', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const carouselEl = fixtureEl.querySelector('#myCarousel') + const carousel = new Carousel(carouselEl, { wrap: true }) + const getActiveId = () => carouselEl.querySelector('.carousel-item.active').getAttribute('id') + + carouselEl.addEventListener('slid.bs.carousel', event => { + const activeId = getActiveId() + + if (activeId === 'two') { + carousel.next() + return + } + + if (activeId === 'three') { + carousel.next() + return + } + + if (activeId === 'one') { + // carousel wrapped around and slid from 3rd to 1st slide + expect(activeId).toEqual('one') + expect(event.from + 1).toEqual(3) + resolve() + } + }) + + carousel.next() + }) + }) + + it('should stay at the start when the prev method is called and wrap is false', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const carouselEl = fixtureEl.querySelector('#myCarousel') + const firstElement = fixtureEl.querySelector('#one') + const carousel = new Carousel(carouselEl, { wrap: false }) + + carouselEl.addEventListener('slid.bs.carousel', () => { + reject(new Error('carousel slid when it should not have slid')) + }) + + carousel.prev() + + setTimeout(() => { + expect(firstElement).toHaveClass('active') + resolve() + }, 10) + }) + }) + + it('should not add touch event listeners if touch = false', () => { + fixtureEl.innerHTML = '
' + + const carouselEl = fixtureEl.querySelector('div') + + const spy = spyOn(Carousel.prototype, '_addTouchEventListeners') + + const carousel = new Carousel(carouselEl, { + touch: false + }) + + expect(spy).not.toHaveBeenCalled() + expect(carousel._swipeHelper).toBeNull() + }) + + it('should not add touch event listeners if touch supported = false', () => { + fixtureEl.innerHTML = '
' + + const carouselEl = fixtureEl.querySelector('div') + spyOn(Swipe, 'isSupported').and.returnValue(false) + + const carousel = new Carousel(carouselEl) + EventHandler.off(carouselEl, Carousel.EVENT_KEY) + + const spy = spyOn(carousel, '_addTouchEventListeners') + + carousel._addEventListeners() + + expect(spy).not.toHaveBeenCalled() + expect(carousel._swipeHelper).toBeNull() + }) + + it('should add touch event listeners by default', () => { + fixtureEl.innerHTML = '
' + + const carouselEl = fixtureEl.querySelector('div') + + spyOn(Carousel.prototype, '_addTouchEventListeners') + + // Headless browser does not support touch events, so need to fake it + // to test that touch events are add properly. + document.documentElement.ontouchstart = noop + const carousel = new Carousel(carouselEl) + + expect(carousel._addTouchEventListeners).toHaveBeenCalled() + }) + + it('should allow swiperight and call _slide (prev) with pointer events', () => { + return new Promise(resolve => { + if (!supportPointerEvent) { + expect().nothing() + resolve() + return + } + + document.documentElement.ontouchstart = noop + document.head.append(stylesCarousel) + Simulator.setType('pointer') + + fixtureEl.innerHTML = [ + '' + ].join('') + + const carouselEl = fixtureEl.querySelector('.carousel') + const item = fixtureEl.querySelector('#item') + const carousel = new Carousel(carouselEl) + + const spy = spyOn(carousel, '_slide').and.callThrough() + + carouselEl.addEventListener('slid.bs.carousel', event => { + expect(item).toHaveClass('active') + expect(spy).toHaveBeenCalledWith('prev') + expect(event.direction).toEqual('right') + stylesCarousel.remove() + delete document.documentElement.ontouchstart + resolve() + }) + + Simulator.gestures.swipe(carouselEl, { + deltaX: 300, + deltaY: 0 + }) + }) + }) + + it('should allow swipeleft and call next with pointer events', () => { + return new Promise(resolve => { + if (!supportPointerEvent) { + expect().nothing() + resolve() + return + } + + document.documentElement.ontouchstart = noop + document.head.append(stylesCarousel) + Simulator.setType('pointer') + + fixtureEl.innerHTML = [ + '' + ].join('') + + const carouselEl = fixtureEl.querySelector('.carousel') + const item = fixtureEl.querySelector('#item') + const carousel = new Carousel(carouselEl) + + const spy = spyOn(carousel, '_slide').and.callThrough() + + carouselEl.addEventListener('slid.bs.carousel', event => { + expect(item).not.toHaveClass('active') + expect(spy).toHaveBeenCalledWith('next') + expect(event.direction).toEqual('left') + stylesCarousel.remove() + delete document.documentElement.ontouchstart + resolve() + }) + + Simulator.gestures.swipe(carouselEl, { + pos: [300, 10], + deltaX: -300, + deltaY: 0 + }) + }) + }) + + it('should allow swiperight and call _slide (prev) with touch events', () => { + return new Promise(resolve => { + Simulator.setType('touch') + clearPointerEvents() + document.documentElement.ontouchstart = noop + + fixtureEl.innerHTML = [ + '' + ].join('') + + const carouselEl = fixtureEl.querySelector('.carousel') + const item = fixtureEl.querySelector('#item') + const carousel = new Carousel(carouselEl) + + const spy = spyOn(carousel, '_slide').and.callThrough() + + carouselEl.addEventListener('slid.bs.carousel', event => { + expect(item).toHaveClass('active') + expect(spy).toHaveBeenCalledWith('prev') + expect(event.direction).toEqual('right') + delete document.documentElement.ontouchstart + restorePointerEvents() + resolve() + }) + + Simulator.gestures.swipe(carouselEl, { + deltaX: 300, + deltaY: 0 + }) + }) + }) + + it('should allow swipeleft and call _slide (next) with touch events', () => { + return new Promise(resolve => { + Simulator.setType('touch') + clearPointerEvents() + document.documentElement.ontouchstart = noop + + fixtureEl.innerHTML = [ + '' + ].join('') + + const carouselEl = fixtureEl.querySelector('.carousel') + const item = fixtureEl.querySelector('#item') + const carousel = new Carousel(carouselEl) + + const spy = spyOn(carousel, '_slide').and.callThrough() + + carouselEl.addEventListener('slid.bs.carousel', event => { + expect(item).not.toHaveClass('active') + expect(spy).toHaveBeenCalledWith('next') + expect(event.direction).toEqual('left') + delete document.documentElement.ontouchstart + restorePointerEvents() + resolve() + }) + + Simulator.gestures.swipe(carouselEl, { + pos: [300, 10], + deltaX: -300, + deltaY: 0 + }) + }) + }) + + it('should not slide when swiping and carousel is sliding', () => { + return new Promise(resolve => { + Simulator.setType('touch') + clearPointerEvents() + document.documentElement.ontouchstart = noop + + fixtureEl.innerHTML = [ + '' + ].join('') + + const carouselEl = fixtureEl.querySelector('.carousel') + const carousel = new Carousel(carouselEl) + carousel._isSliding = true + + const spy = spyOn(EventHandler, 'trigger') + + Simulator.gestures.swipe(carouselEl, { + deltaX: 300, + deltaY: 0 + }) + + Simulator.gestures.swipe(carouselEl, { + pos: [300, 10], + deltaX: -300, + deltaY: 0 + }) + + setTimeout(() => { + expect(spy).not.toHaveBeenCalled() + delete document.documentElement.ontouchstart + restorePointerEvents() + resolve() + }, 300) + }) + }) + + it('should not allow pinch with touch events', () => { + return new Promise(resolve => { + Simulator.setType('touch') + clearPointerEvents() + document.documentElement.ontouchstart = noop + + fixtureEl.innerHTML = '' + + const carouselEl = fixtureEl.querySelector('.carousel') + const carousel = new Carousel(carouselEl) + + Simulator.gestures.swipe(carouselEl, { + pos: [300, 10], + deltaX: -300, + deltaY: 0, + touches: 2 + }, () => { + restorePointerEvents() + delete document.documentElement.ontouchstart + expect(carousel._swipeHelper._deltaX).toEqual(0) + resolve() + }) + }) + }) + + it('should call pause method on mouse over with pause equal to hover', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const carouselEl = fixtureEl.querySelector('.carousel') + const carousel = new Carousel(carouselEl) + + const spy = spyOn(carousel, 'pause') + + const mouseOverEvent = createEvent('mouseover') + carouselEl.dispatchEvent(mouseOverEvent) + + setTimeout(() => { + expect(spy).toHaveBeenCalled() + resolve() + }, 10) + }) + }) + + it('should call `maybeEnableCycle` on mouse out with pause equal to hover', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const carouselEl = fixtureEl.querySelector('.carousel') + const carousel = new Carousel(carouselEl) + + const spyEnable = spyOn(carousel, '_maybeEnableCycle').and.callThrough() + const spyCycle = spyOn(carousel, 'cycle') + + const mouseOutEvent = createEvent('mouseout') + carouselEl.dispatchEvent(mouseOutEvent) + + setTimeout(() => { + expect(spyEnable).toHaveBeenCalled() + expect(spyCycle).toHaveBeenCalled() + resolve() + }, 10) + }) + }) + }) + + describe('next', () => { + it('should not slide if the carousel is sliding', () => { + fixtureEl.innerHTML = '
' + + const carouselEl = fixtureEl.querySelector('div') + const carousel = new Carousel(carouselEl, {}) + + const spy = spyOn(EventHandler, 'trigger') + + carousel._isSliding = true + carousel.next() + + expect(spy).not.toHaveBeenCalled() + }) + + it('should not fire slid when slide is prevented', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + + const carouselEl = fixtureEl.querySelector('div') + const carousel = new Carousel(carouselEl, {}) + let slidEvent = false + + const doneTest = () => { + setTimeout(() => { + expect(slidEvent).toBeFalse() + resolve() + }, 20) + } + + carouselEl.addEventListener('slide.bs.carousel', event => { + event.preventDefault() + doneTest() + }) + + carouselEl.addEventListener('slid.bs.carousel', () => { + slidEvent = true + }) + + carousel.next() + }) + }) + + it('should fire slide event with: direction, relatedTarget, from and to', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const carouselEl = fixtureEl.querySelector('#myCarousel') + const carousel = new Carousel(carouselEl, {}) + + const onSlide = event => { + expect(event.direction).toEqual('left') + expect(event.relatedTarget).toHaveClass('carousel-item') + expect(event.from).toEqual(0) + expect(event.to).toEqual(1) + + carouselEl.removeEventListener('slide.bs.carousel', onSlide) + carouselEl.addEventListener('slide.bs.carousel', onSlide2) + + carousel.prev() + } + + const onSlide2 = event => { + expect(event.direction).toEqual('right') + resolve() + } + + carouselEl.addEventListener('slide.bs.carousel', onSlide) + carousel.next() + }) + }) + + it('should fire slid event with: direction, relatedTarget, from and to', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const carouselEl = fixtureEl.querySelector('#myCarousel') + const carousel = new Carousel(carouselEl, {}) + + const onSlid = event => { + expect(event.direction).toEqual('left') + expect(event.relatedTarget).toHaveClass('carousel-item') + expect(event.from).toEqual(0) + expect(event.to).toEqual(1) + + carouselEl.removeEventListener('slid.bs.carousel', onSlid) + carouselEl.addEventListener('slid.bs.carousel', onSlid2) + + carousel.prev() + } + + const onSlid2 = event => { + expect(event.direction).toEqual('right') + resolve() + } + + carouselEl.addEventListener('slid.bs.carousel', onSlid) + carousel.next() + }) + }) + + it('should update the active element to the next item before sliding', () => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const carouselEl = fixtureEl.querySelector('#myCarousel') + const secondItemEl = fixtureEl.querySelector('#secondItem') + const carousel = new Carousel(carouselEl) + + carousel.next() + + expect(carousel._activeElement).toEqual(secondItemEl) + }) + + it('should continue cycling if it was already', () => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const carouselEl = fixtureEl.querySelector('#myCarousel') + const carousel = new Carousel(carouselEl) + const spy = spyOn(carousel, 'cycle') + + carousel.next() + expect(spy).not.toHaveBeenCalled() + + carousel.cycle() + carousel.next() + expect(spy).toHaveBeenCalledTimes(1) + }) + + it('should update indicators if present', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const carouselEl = fixtureEl.querySelector('#myCarousel') + const firstIndicator = fixtureEl.querySelector('#firstIndicator') + const secondIndicator = fixtureEl.querySelector('#secondIndicator') + const carousel = new Carousel(carouselEl) + + carouselEl.addEventListener('slid.bs.carousel', () => { + expect(firstIndicator).not.toHaveClass('active') + expect(firstIndicator.hasAttribute('aria-current')).toBeFalse() + expect(secondIndicator).toHaveClass('active') + expect(secondIndicator.getAttribute('aria-current')).toEqual('true') + resolve() + }) + + carousel.next() + }) + }) + + it('should call next()/prev() instance methods when clicking the respective direction buttons', () => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const carouselEl = fixtureEl.querySelector('#carousel') + const prevBtnEl = fixtureEl.querySelector('.carousel-control-prev') + const nextBtnEl = fixtureEl.querySelector('.carousel-control-next') + + const carousel = new Carousel(carouselEl) + const nextSpy = spyOn(carousel, 'next') + const prevSpy = spyOn(carousel, 'prev') + const spyEnable = spyOn(carousel, '_maybeEnableCycle') + + nextBtnEl.click() + prevBtnEl.click() + + expect(nextSpy).toHaveBeenCalled() + expect(prevSpy).toHaveBeenCalled() + expect(spyEnable).toHaveBeenCalled() + }) + }) + + describe('nextWhenVisible', () => { + it('should not call next when the page is not visible', () => { + fixtureEl.innerHTML = [ + '
', + ' ', + '
' + ].join('') + + const carouselEl = fixtureEl.querySelector('.carousel') + const carousel = new Carousel(carouselEl) + + const spy = spyOn(carousel, 'next') + + carousel.nextWhenVisible() + + expect(spy).not.toHaveBeenCalled() + }) + }) + + describe('prev', () => { + it('should not slide if the carousel is sliding', () => { + fixtureEl.innerHTML = '
' + + const carouselEl = fixtureEl.querySelector('div') + const carousel = new Carousel(carouselEl, {}) + + const spy = spyOn(EventHandler, 'trigger') + + carousel._isSliding = true + carousel.prev() + + expect(spy).not.toHaveBeenCalled() + }) + }) + + describe('pause', () => { + it('should trigger transitionend if the carousel have carousel-item-next or carousel-item-prev class, cause is sliding', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const carouselEl = fixtureEl.querySelector('#myCarousel') + const carousel = new Carousel(carouselEl) + const spy = spyOn(carousel, '_clearInterval') + + carouselEl.addEventListener('transitionend', () => { + expect(spy).toHaveBeenCalled() + resolve() + }) + + carousel._slide('next') + carousel.pause() + }) + }) + }) + + describe('cycle', () => { + it('should set an interval', () => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const carouselEl = fixtureEl.querySelector('#myCarousel') + const carousel = new Carousel(carouselEl) + + const spy = spyOn(window, 'setInterval').and.callThrough() + + carousel.cycle() + + expect(spy).toHaveBeenCalled() + }) + + it('should clear interval if there is one', () => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const carouselEl = fixtureEl.querySelector('#myCarousel') + const carousel = new Carousel(carouselEl) + + carousel._interval = setInterval(noop, 10) + + const spySet = spyOn(window, 'setInterval').and.callThrough() + const spyClear = spyOn(window, 'clearInterval').and.callThrough() + + carousel.cycle() + + expect(spySet).toHaveBeenCalled() + expect(spyClear).toHaveBeenCalled() + }) + + it('should get interval from data attribute on the active item element', () => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const carouselEl = fixtureEl.querySelector('#myCarousel') + const secondItemEl = fixtureEl.querySelector('#secondItem') + const carousel = new Carousel(carouselEl, { + interval: 1814 + }) + + expect(carousel._config.interval).toEqual(1814) + + carousel.cycle() + + expect(carousel._config.interval).toEqual(7) + + carousel._activeElement = secondItemEl + carousel.cycle() + + expect(carousel._config.interval).toEqual(9385) + }) + }) + + describe('to', () => { + it('should go directly to the provided index', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const carouselEl = fixtureEl.querySelector('#myCarousel') + const carousel = new Carousel(carouselEl, {}) + + expect(fixtureEl.querySelector('.active')).toEqual(fixtureEl.querySelector('#item1')) + + carousel.to(2) + + carouselEl.addEventListener('slid.bs.carousel', () => { + expect(fixtureEl.querySelector('.active')).toEqual(fixtureEl.querySelector('#item3')) + resolve() + }) + }) + }) + + it('should return to a previous slide if the provided index is lower than the current', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const carouselEl = fixtureEl.querySelector('#myCarousel') + const carousel = new Carousel(carouselEl, {}) + + expect(fixtureEl.querySelector('.active')).toEqual(fixtureEl.querySelector('#item3')) + + carousel.to(1) + + carouselEl.addEventListener('slid.bs.carousel', () => { + expect(fixtureEl.querySelector('.active')).toEqual(fixtureEl.querySelector('#item2')) + resolve() + }) + }) + }) + + it('should do nothing if a wrong index is provided', () => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const carouselEl = fixtureEl.querySelector('#myCarousel') + const carousel = new Carousel(carouselEl, {}) + + const spy = spyOn(carousel, '_slide') + + carousel.to(25) + + expect(spy).not.toHaveBeenCalled() + + spy.calls.reset() + + carousel.to(-5) + + expect(spy).not.toHaveBeenCalled() + }) + + it('should not continue if the provided is the same compare to the current one', () => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const carouselEl = fixtureEl.querySelector('#myCarousel') + const carousel = new Carousel(carouselEl, {}) + + const spy = spyOn(carousel, '_slide') + + carousel.to(0) + + expect(spy).not.toHaveBeenCalled() + }) + + it('should wait before performing to if a slide is sliding', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const carouselEl = fixtureEl.querySelector('#myCarousel') + const carousel = new Carousel(carouselEl, {}) + + const spyOne = spyOn(EventHandler, 'one').and.callThrough() + const spySlide = spyOn(carousel, '_slide') + + carousel._isSliding = true + carousel.to(1) + + expect(spySlide).not.toHaveBeenCalled() + expect(spyOne).toHaveBeenCalled() + + const spyTo = spyOn(carousel, 'to') + + EventHandler.trigger(carouselEl, 'slid.bs.carousel') + + setTimeout(() => { + expect(spyTo).toHaveBeenCalledWith(1) + resolve() + }) + }) + }) + }) + + describe('rtl function', () => { + it('"_directionToOrder" and "_orderToDirection" must return the right results', () => { + fixtureEl.innerHTML = '
' + + const carouselEl = fixtureEl.querySelector('div') + const carousel = new Carousel(carouselEl, {}) + + expect(carousel._directionToOrder('left')).toEqual('next') + expect(carousel._directionToOrder('right')).toEqual('prev') + + expect(carousel._orderToDirection('next')).toEqual('left') + expect(carousel._orderToDirection('prev')).toEqual('right') + }) + + it('"_directionToOrder" and "_orderToDirection" must return the right results when rtl=true', () => { + document.documentElement.dir = 'rtl' + fixtureEl.innerHTML = '
' + + const carouselEl = fixtureEl.querySelector('div') + const carousel = new Carousel(carouselEl, {}) + expect(isRTL()).toBeTrue() + + expect(carousel._directionToOrder('left')).toEqual('prev') + expect(carousel._directionToOrder('right')).toEqual('next') + + expect(carousel._orderToDirection('next')).toEqual('right') + expect(carousel._orderToDirection('prev')).toEqual('left') + document.documentElement.dir = 'ltl' + }) + + it('"_slide" has to call _directionToOrder and "_orderToDirection"', () => { + fixtureEl.innerHTML = '
' + + const carouselEl = fixtureEl.querySelector('div') + const carousel = new Carousel(carouselEl, {}) + + const spy = spyOn(carousel, '_orderToDirection').and.callThrough() + + carousel._slide(carousel._directionToOrder('left')) + expect(spy).toHaveBeenCalledWith('next') + + carousel._slide(carousel._directionToOrder('right')) + expect(spy).toHaveBeenCalledWith('prev') + }) + + it('"_slide" has to call "_directionToOrder" and "_orderToDirection" when rtl=true', () => { + document.documentElement.dir = 'rtl' + fixtureEl.innerHTML = '
' + + const carouselEl = fixtureEl.querySelector('div') + const carousel = new Carousel(carouselEl, {}) + const spy = spyOn(carousel, '_orderToDirection').and.callThrough() + + carousel._slide(carousel._directionToOrder('left')) + expect(spy).toHaveBeenCalledWith('prev') + + carousel._slide(carousel._directionToOrder('right')) + expect(spy).toHaveBeenCalledWith('next') + + document.documentElement.dir = 'ltl' + }) + }) + + describe('dispose', () => { + it('should destroy a carousel', () => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const carouselEl = fixtureEl.querySelector('#myCarousel') + const addEventSpy = spyOn(carouselEl, 'addEventListener').and.callThrough() + const removeEventSpy = spyOn(EventHandler, 'off').and.callThrough() + + // Headless browser does not support touch events, so need to fake it + // to test that touch events are add/removed properly. + document.documentElement.ontouchstart = noop + + const carousel = new Carousel(carouselEl) + const swipeHelperSpy = spyOn(carousel._swipeHelper, 'dispose').and.callThrough() + + const expectedArgs = [ + ['keydown', jasmine.any(Function), jasmine.any(Boolean)], + ['mouseover', jasmine.any(Function), jasmine.any(Boolean)], + ['mouseout', jasmine.any(Function), jasmine.any(Boolean)], + ...(carousel._swipeHelper._supportPointerEvents ? + [ + ['pointerdown', jasmine.any(Function), jasmine.any(Boolean)], + ['pointerup', jasmine.any(Function), jasmine.any(Boolean)] + ] : + [ + ['touchstart', jasmine.any(Function), jasmine.any(Boolean)], + ['touchmove', jasmine.any(Function), jasmine.any(Boolean)], + ['touchend', jasmine.any(Function), jasmine.any(Boolean)] + ]) + ] + + expect(addEventSpy.calls.allArgs()).toEqual(expectedArgs) + + carousel.dispose() + + expect(carousel._swipeHelper).toBeNull() + expect(removeEventSpy).toHaveBeenCalledWith(carouselEl, Carousel.EVENT_KEY) + expect(swipeHelperSpy).toHaveBeenCalled() + + delete document.documentElement.ontouchstart + }) + }) + + describe('getInstance', () => { + it('should return carousel instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const carousel = new Carousel(div) + + expect(Carousel.getInstance(div)).toEqual(carousel) + expect(Carousel.getInstance(div)).toBeInstanceOf(Carousel) + }) + + it('should return null when there is no carousel instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(Carousel.getInstance(div)).toBeNull() + }) + }) + + describe('getOrCreateInstance', () => { + it('should return carousel instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const carousel = new Carousel(div) + + expect(Carousel.getOrCreateInstance(div)).toEqual(carousel) + expect(Carousel.getInstance(div)).toEqual(Carousel.getOrCreateInstance(div, {})) + expect(Carousel.getOrCreateInstance(div)).toBeInstanceOf(Carousel) + }) + + it('should return new instance when there is no carousel instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(Carousel.getInstance(div)).toBeNull() + expect(Carousel.getOrCreateInstance(div)).toBeInstanceOf(Carousel) + }) + + it('should return new instance when there is no carousel instance with given configuration', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(Carousel.getInstance(div)).toBeNull() + const carousel = Carousel.getOrCreateInstance(div, { + interval: 1 + }) + expect(carousel).toBeInstanceOf(Carousel) + + expect(carousel._config.interval).toEqual(1) + }) + + it('should return the instance when exists without given configuration', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const carousel = new Carousel(div, { + interval: 1 + }) + expect(Carousel.getInstance(div)).toEqual(carousel) + + const carousel2 = Carousel.getOrCreateInstance(div, { + interval: 2 + }) + expect(carousel).toBeInstanceOf(Carousel) + expect(carousel2).toEqual(carousel) + + expect(carousel2._config.interval).toEqual(1) + }) + }) + + describe('jQueryInterface', () => { + it('should create a carousel', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + jQueryMock.fn.carousel = Carousel.jQueryInterface + jQueryMock.elements = [div] + + jQueryMock.fn.carousel.call(jQueryMock) + + expect(Carousel.getInstance(div)).not.toBeNull() + }) + + it('should not re create a carousel', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const carousel = new Carousel(div) + + jQueryMock.fn.carousel = Carousel.jQueryInterface + jQueryMock.elements = [div] + + jQueryMock.fn.carousel.call(jQueryMock) + + expect(Carousel.getInstance(div)).toEqual(carousel) + }) + + it('should call to if the config is a number', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const carousel = new Carousel(div) + const slideTo = 2 + + const spy = spyOn(carousel, 'to') + + jQueryMock.fn.carousel = Carousel.jQueryInterface + jQueryMock.elements = [div] + + jQueryMock.fn.carousel.call(jQueryMock, slideTo) + + expect(spy).toHaveBeenCalledWith(slideTo) + }) + + it('should throw error on undefined method', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const action = 'undefinedMethod' + + jQueryMock.fn.carousel = Carousel.jQueryInterface + jQueryMock.elements = [div] + + expect(() => { + jQueryMock.fn.carousel.call(jQueryMock, action) + }).toThrowError(TypeError, `No method named "${action}"`) + }) + }) + + describe('data-api', () => { + it('should init carousels with data-bs-ride="carousel" on load', () => { + fixtureEl.innerHTML = '
' + + const carouselEl = fixtureEl.querySelector('div') + const loadEvent = createEvent('load') + + window.dispatchEvent(loadEvent) + const carousel = Carousel.getInstance(carouselEl) + expect(carousel._interval).not.toBeNull() + }) + + it('should create carousel and go to the next slide on click (with real button controls)', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const next = fixtureEl.querySelector('#next') + const item2 = fixtureEl.querySelector('#item2') + + next.click() + + setTimeout(() => { + expect(item2).toHaveClass('active') + resolve() + }, 10) + }) + }) + + it('should create carousel and go to the next slide on click (using links as controls)', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const next = fixtureEl.querySelector('#next') + const item2 = fixtureEl.querySelector('#item2') + + next.click() + + setTimeout(() => { + expect(item2).toHaveClass('active') + resolve() + }, 10) + }) + }) + + it('should create carousel and go to the next slide on click with data-bs-slide-to', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const next = fixtureEl.querySelector('#next') + const item2 = fixtureEl.querySelector('#item2') + + next.click() + + setTimeout(() => { + expect(item2).toHaveClass('active') + expect(Carousel.getInstance('#myCarousel')._interval).not.toBeNull() + resolve() + }, 10) + }) + }) + + it('should do nothing if no selector on click on arrows', () => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const next = fixtureEl.querySelector('#next') + + next.click() + + expect().nothing() + }) + + it('should do nothing if no carousel class on click on arrows', () => { + fixtureEl.innerHTML = [ + '
', + ' ', + ' ', + ' ', + '
' + ].join('') + + const next = fixtureEl.querySelector('#next') + + next.click() + + expect().nothing() + }) + }) +}) diff --git a/js/tests/unit/collapse.spec.js b/js/tests/unit/collapse.spec.js new file mode 100644 index 0000000..9c86719 --- /dev/null +++ b/js/tests/unit/collapse.spec.js @@ -0,0 +1,1062 @@ +import Collapse from '../../src/collapse' +import EventHandler from '../../src/dom/event-handler' +import { clearFixture, getFixture, jQueryMock } from '../helpers/fixture' + +describe('Collapse', () => { + let fixtureEl + + beforeAll(() => { + fixtureEl = getFixture() + }) + + afterEach(() => { + clearFixture() + }) + + describe('VERSION', () => { + it('should return plugin version', () => { + expect(Collapse.VERSION).toEqual(jasmine.any(String)) + }) + }) + + describe('Default', () => { + it('should return plugin default config', () => { + expect(Collapse.Default).toEqual(jasmine.any(Object)) + }) + }) + + describe('DATA_KEY', () => { + it('should return plugin data key', () => { + expect(Collapse.DATA_KEY).toEqual('bs.collapse') + }) + }) + + describe('constructor', () => { + it('should take care of element either passed as a CSS selector or DOM element', () => { + fixtureEl.innerHTML = '
' + + const collapseEl = fixtureEl.querySelector('div.my-collapse') + const collapseBySelector = new Collapse('div.my-collapse') + const collapseByElement = new Collapse(collapseEl) + + expect(collapseBySelector._element).toEqual(collapseEl) + expect(collapseByElement._element).toEqual(collapseEl) + }) + + it('should allow jquery object in parent config', () => { + fixtureEl.innerHTML = [ + '
', + '
', + ' Toggle item', + '
Lorem ipsum
', + '
', + '
' + ].join('') + + const collapseEl = fixtureEl.querySelector('div.collapse') + const myCollapseEl = fixtureEl.querySelector('.my-collapse') + const fakejQueryObject = { + 0: myCollapseEl, + jquery: 'foo' + } + const collapse = new Collapse(collapseEl, { + parent: fakejQueryObject + }) + + expect(collapse._config.parent).toEqual(myCollapseEl) + }) + + it('should allow non jquery object in parent config', () => { + fixtureEl.innerHTML = [ + '
', + '
', + ' Toggle item', + '
Lorem ipsum
', + '
', + '
' + ].join('') + + const collapseEl = fixtureEl.querySelector('div.collapse') + const myCollapseEl = fixtureEl.querySelector('.my-collapse') + const collapse = new Collapse(collapseEl, { + parent: myCollapseEl + }) + + expect(collapse._config.parent).toEqual(myCollapseEl) + }) + + it('should allow string selector in parent config', () => { + fixtureEl.innerHTML = [ + '
', + '
', + ' Toggle item', + '
Lorem ipsum
', + '
', + '
' + ].join('') + + const collapseEl = fixtureEl.querySelector('div.collapse') + const myCollapseEl = fixtureEl.querySelector('.my-collapse') + const collapse = new Collapse(collapseEl, { + parent: 'div.my-collapse' + }) + + expect(collapse._config.parent).toEqual(myCollapseEl) + }) + }) + + describe('toggle', () => { + it('should call show method if show class is not present', () => { + fixtureEl.innerHTML = '
' + + const collapseEl = fixtureEl.querySelector('div') + const collapse = new Collapse(collapseEl) + + const spy = spyOn(collapse, 'show') + + collapse.toggle() + + expect(spy).toHaveBeenCalled() + }) + + it('should call hide method if show class is present', () => { + fixtureEl.innerHTML = '
' + + const collapseEl = fixtureEl.querySelector('.show') + const collapse = new Collapse(collapseEl, { + toggle: false + }) + + const spy = spyOn(collapse, 'hide') + + collapse.toggle() + + expect(spy).toHaveBeenCalled() + }) + + it('should find collapse children if they have collapse class too not only data-bs-parent', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '
', + '
', + ' Toggle item 1', + '
Lorem ipsum 1
', + '
', + '
', + ' Toggle item 2', + '
Lorem ipsum 2
', + '
', + '
' + ].join('') + + const parent = fixtureEl.querySelector('.my-collapse') + const collapseEl1 = fixtureEl.querySelector('#collapse1') + const collapseEl2 = fixtureEl.querySelector('#collapse2') + + const collapseList = [].concat(...fixtureEl.querySelectorAll('.collapse')) + .map(el => new Collapse(el, { + parent, + toggle: false + })) + + collapseEl2.addEventListener('shown.bs.collapse', () => { + expect(collapseEl2).toHaveClass('show') + expect(collapseEl1).not.toHaveClass('show') + resolve() + }) + + collapseList[1].toggle() + }) + }) + }) + + describe('show', () => { + it('should do nothing if is transitioning', () => { + fixtureEl.innerHTML = '
' + + const spy = spyOn(EventHandler, 'trigger') + + const collapseEl = fixtureEl.querySelector('div') + const collapse = new Collapse(collapseEl, { + toggle: false + }) + + collapse._isTransitioning = true + collapse.show() + + expect(spy).not.toHaveBeenCalled() + }) + + it('should do nothing if already shown', () => { + fixtureEl.innerHTML = '
' + + const spy = spyOn(EventHandler, 'trigger') + + const collapseEl = fixtureEl.querySelector('div') + const collapse = new Collapse(collapseEl, { + toggle: false + }) + + collapse.show() + + expect(spy).not.toHaveBeenCalled() + }) + + it('should show a collapsed element', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + + const collapseEl = fixtureEl.querySelector('div') + const collapse = new Collapse(collapseEl, { + toggle: false + }) + + collapseEl.addEventListener('show.bs.collapse', () => { + expect(collapseEl.style.height).toEqual('0px') + }) + collapseEl.addEventListener('shown.bs.collapse', () => { + expect(collapseEl).toHaveClass('show') + expect(collapseEl.style.height).toEqual('') + resolve() + }) + + collapse.show() + }) + }) + + it('should show a collapsed element on width', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + + const collapseEl = fixtureEl.querySelector('div') + const collapse = new Collapse(collapseEl, { + toggle: false + }) + + collapseEl.addEventListener('show.bs.collapse', () => { + expect(collapseEl.style.width).toEqual('0px') + }) + collapseEl.addEventListener('shown.bs.collapse', () => { + expect(collapseEl).toHaveClass('show') + expect(collapseEl.style.width).toEqual('') + resolve() + }) + + collapse.show() + }) + }) + + it('should collapse only the first collapse', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '
', + '
', + '
', + '
', + '
', + '
' + ].join('') + + const el1 = fixtureEl.querySelector('#collapse1') + const el2 = fixtureEl.querySelector('#collapse2') + const collapse = new Collapse(el1, { + toggle: false + }) + + el1.addEventListener('shown.bs.collapse', () => { + expect(el1).toHaveClass('show') + expect(el2).toHaveClass('show') + resolve() + }) + + collapse.show() + }) + }) + + it('should be able to handle toggling of other children siblings', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '
', + '
', + ' ', + '
', + '
', + '
', + '
', + '
', + '
', + ' ', + '
', + '
', + '
content
', + '
', + '
', + '
', + '
', + ' ', + '
', + '
', + '
content
', + '
', + '
', + '
', + '
', + '
', + '
' + ].join('') + + const el = selector => fixtureEl.querySelector(selector) + + const parentBtn = el('[data-bs-target="#parentContent"]') + const childBtn1 = el('[data-bs-target="#childContent1"]') + const childBtn2 = el('[data-bs-target="#childContent2"]') + + const parentCollapseEl = el('#parentContent') + const childCollapseEl1 = el('#childContent1') + const childCollapseEl2 = el('#childContent2') + + parentCollapseEl.addEventListener('shown.bs.collapse', () => { + expect(parentCollapseEl).toHaveClass('show') + childBtn1.click() + }) + childCollapseEl1.addEventListener('shown.bs.collapse', () => { + expect(childCollapseEl1).toHaveClass('show') + childBtn2.click() + }) + childCollapseEl2.addEventListener('shown.bs.collapse', () => { + expect(childCollapseEl2).toHaveClass('show') + expect(childCollapseEl1).not.toHaveClass('show') + resolve() + }) + + parentBtn.click() + }) + }) + + it('should not change tab tabpanels descendants on accordion', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '
', + '
', + '

', + ' ', + '

', + '
', + '
', + ' ', + ' ', + '
', + '
', + '
', + '
' + ].join('') + + const el = fixtureEl.querySelector('#collapseOne') + const activeTabPane = fixtureEl.querySelector('#nav-home') + const collapse = new Collapse(el) + let times = 1 + + el.addEventListener('hidden.bs.collapse', () => { + collapse.show() + }) + + el.addEventListener('shown.bs.collapse', () => { + expect(activeTabPane).toHaveClass('show') + times++ + if (times === 2) { + resolve() + } + + collapse.hide() + }) + + collapse.show() + }) + }) + + it('should not fire shown when show is prevented', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = '
' + + const collapseEl = fixtureEl.querySelector('div') + const collapse = new Collapse(collapseEl, { + toggle: false + }) + + const expectEnd = () => { + setTimeout(() => { + expect().nothing() + resolve() + }, 10) + } + + collapseEl.addEventListener('show.bs.collapse', event => { + event.preventDefault() + expectEnd() + }) + + collapseEl.addEventListener('shown.bs.collapse', () => { + reject(new Error('should not fire shown event')) + }) + + collapse.show() + }) + }) + }) + + describe('hide', () => { + it('should do nothing if is transitioning', () => { + fixtureEl.innerHTML = '
' + + const spy = spyOn(EventHandler, 'trigger') + + const collapseEl = fixtureEl.querySelector('div') + const collapse = new Collapse(collapseEl, { + toggle: false + }) + + collapse._isTransitioning = true + collapse.hide() + + expect(spy).not.toHaveBeenCalled() + }) + + it('should do nothing if already shown', () => { + fixtureEl.innerHTML = '
' + + const spy = spyOn(EventHandler, 'trigger') + + const collapseEl = fixtureEl.querySelector('div') + const collapse = new Collapse(collapseEl, { + toggle: false + }) + + collapse.hide() + + expect(spy).not.toHaveBeenCalled() + }) + + it('should hide a collapsed element', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + + const collapseEl = fixtureEl.querySelector('div') + const collapse = new Collapse(collapseEl, { + toggle: false + }) + + collapseEl.addEventListener('hidden.bs.collapse', () => { + expect(collapseEl).not.toHaveClass('show') + expect(collapseEl.style.height).toEqual('') + resolve() + }) + + collapse.hide() + }) + }) + + it('should not fire hidden when hide is prevented', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = '
' + + const collapseEl = fixtureEl.querySelector('div') + const collapse = new Collapse(collapseEl, { + toggle: false + }) + + const expectEnd = () => { + setTimeout(() => { + expect().nothing() + resolve() + }, 10) + } + + collapseEl.addEventListener('hide.bs.collapse', event => { + event.preventDefault() + expectEnd() + }) + + collapseEl.addEventListener('hidden.bs.collapse', () => { + reject(new Error('should not fire hidden event')) + }) + + collapse.hide() + }) + }) + }) + + describe('dispose', () => { + it('should destroy a collapse', () => { + fixtureEl.innerHTML = '
' + + const collapseEl = fixtureEl.querySelector('div') + const collapse = new Collapse(collapseEl, { + toggle: false + }) + + expect(Collapse.getInstance(collapseEl)).toEqual(collapse) + + collapse.dispose() + + expect(Collapse.getInstance(collapseEl)).toBeNull() + }) + }) + + describe('data-api', () => { + it('should prevent url change if click on nested elements', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '
' + ].join('') + + const triggerEl = fixtureEl.querySelector('a') + const nestedTriggerEl = fixtureEl.querySelector('#nested') + + const spy = spyOn(Event.prototype, 'preventDefault').and.callThrough() + + triggerEl.addEventListener('click', event => { + expect(event.target.isEqualNode(nestedTriggerEl)).toBeTrue() + expect(event.delegateTarget.isEqualNode(triggerEl)).toBeTrue() + expect(spy).toHaveBeenCalled() + resolve() + }) + + nestedTriggerEl.click() + }) + }) + + it('should show multiple collapsed elements', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '
', + '
' + ].join('') + + const trigger = fixtureEl.querySelector('a') + const collapse1 = fixtureEl.querySelector('#collapse1') + const collapse2 = fixtureEl.querySelector('#collapse2') + + collapse2.addEventListener('shown.bs.collapse', () => { + expect(trigger.getAttribute('aria-expanded')).toEqual('true') + expect(trigger).not.toHaveClass('collapsed') + expect(collapse1).toHaveClass('show') + expect(collapse1).toHaveClass('show') + resolve() + }) + + trigger.click() + }) + }) + + it('should hide multiple collapsed elements', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '
', + '
' + ].join('') + + const trigger = fixtureEl.querySelector('a') + const collapse1 = fixtureEl.querySelector('#collapse1') + const collapse2 = fixtureEl.querySelector('#collapse2') + + collapse2.addEventListener('hidden.bs.collapse', () => { + expect(trigger.getAttribute('aria-expanded')).toEqual('false') + expect(trigger).toHaveClass('collapsed') + expect(collapse1).not.toHaveClass('show') + expect(collapse1).not.toHaveClass('show') + resolve() + }) + + trigger.click() + }) + }) + + it('should remove "collapsed" class from target when collapse is shown', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '', + '
' + ].join('') + + const link1 = fixtureEl.querySelector('#link1') + const link2 = fixtureEl.querySelector('#link2') + const collapseTest1 = fixtureEl.querySelector('#test1') + + collapseTest1.addEventListener('shown.bs.collapse', () => { + expect(link1.getAttribute('aria-expanded')).toEqual('true') + expect(link2.getAttribute('aria-expanded')).toEqual('true') + expect(link1).not.toHaveClass('collapsed') + expect(link2).not.toHaveClass('collapsed') + resolve() + }) + + link1.click() + }) + }) + + it('should add "collapsed" class to target when collapse is hidden', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '', + '
' + ].join('') + + const link1 = fixtureEl.querySelector('#link1') + const link2 = fixtureEl.querySelector('#link2') + const collapseTest1 = fixtureEl.querySelector('#test1') + + collapseTest1.addEventListener('hidden.bs.collapse', () => { + expect(link1.getAttribute('aria-expanded')).toEqual('false') + expect(link2.getAttribute('aria-expanded')).toEqual('false') + expect(link1).toHaveClass('collapsed') + expect(link2).toHaveClass('collapsed') + resolve() + }) + + link1.click() + }) + }) + + it('should allow accordion to use children other than card', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '
', + '
', + ' ', + '
', + '
', + '
', + ' ', + '
', + '
', + '
' + ].join('') + + const trigger = fixtureEl.querySelector('#linkTrigger') + const triggerTwo = fixtureEl.querySelector('#linkTriggerTwo') + const collapseOne = fixtureEl.querySelector('#collapseOne') + const collapseTwo = fixtureEl.querySelector('#collapseTwo') + + collapseOne.addEventListener('shown.bs.collapse', () => { + expect(collapseOne).toHaveClass('show') + expect(collapseTwo).not.toHaveClass('show') + + collapseTwo.addEventListener('shown.bs.collapse', () => { + expect(collapseOne).not.toHaveClass('show') + expect(collapseTwo).toHaveClass('show') + resolve() + }) + + triggerTwo.click() + }) + + trigger.click() + }) + }) + + it('should not prevent event for input', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '
' + ].join('') + + const target = fixtureEl.querySelector('input') + const collapseEl = fixtureEl.querySelector('#collapsediv1') + + collapseEl.addEventListener('shown.bs.collapse', () => { + expect(collapseEl).toHaveClass('show') + expect(target.checked).toBeTrue() + resolve() + }) + + target.click() + }) + }) + + it('should allow accordion to contain nested elements', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '
', + '
', + '
', + '
', + ' ', + '
', + '
', + '
', + '
', + '
', + ' ', + '
', + '
', + '
', + '
', + '
' + ].join('') + + const triggerEl = fixtureEl.querySelector('#linkTrigger') + const triggerTwoEl = fixtureEl.querySelector('#linkTriggerTwo') + const collapseOneEl = fixtureEl.querySelector('#collapseOne') + const collapseTwoEl = fixtureEl.querySelector('#collapseTwo') + + collapseOneEl.addEventListener('shown.bs.collapse', () => { + expect(collapseOneEl).toHaveClass('show') + expect(triggerEl).not.toHaveClass('collapsed') + expect(triggerEl.getAttribute('aria-expanded')).toEqual('true') + + expect(collapseTwoEl).not.toHaveClass('show') + expect(triggerTwoEl).toHaveClass('collapsed') + expect(triggerTwoEl.getAttribute('aria-expanded')).toEqual('false') + + collapseTwoEl.addEventListener('shown.bs.collapse', () => { + expect(collapseOneEl).not.toHaveClass('show') + expect(triggerEl).toHaveClass('collapsed') + expect(triggerEl.getAttribute('aria-expanded')).toEqual('false') + + expect(collapseTwoEl).toHaveClass('show') + expect(triggerTwoEl).not.toHaveClass('collapsed') + expect(triggerTwoEl.getAttribute('aria-expanded')).toEqual('true') + resolve() + }) + + triggerTwoEl.click() + }) + + triggerEl.click() + }) + }) + + it('should allow accordion to target multiple elements', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '
', + ' ', + ' ', + '
', + '
', + '
', + '
', + '
' + ].join('') + + const trigger = fixtureEl.querySelector('#linkTriggerOne') + const triggerTwo = fixtureEl.querySelector('#linkTriggerTwo') + const collapseOneOne = fixtureEl.querySelector('#collapseOneOne') + const collapseOneTwo = fixtureEl.querySelector('#collapseOneTwo') + const collapseTwoOne = fixtureEl.querySelector('#collapseTwoOne') + const collapseTwoTwo = fixtureEl.querySelector('#collapseTwoTwo') + const collapsedElements = { + one: false, + two: false + } + + function firstTest() { + expect(collapseOneOne).toHaveClass('show') + expect(collapseOneTwo).toHaveClass('show') + + expect(collapseTwoOne).not.toHaveClass('show') + expect(collapseTwoTwo).not.toHaveClass('show') + + triggerTwo.click() + } + + function secondTest() { + expect(collapseOneOne).not.toHaveClass('show') + expect(collapseOneTwo).not.toHaveClass('show') + + expect(collapseTwoOne).toHaveClass('show') + expect(collapseTwoTwo).toHaveClass('show') + resolve() + } + + collapseOneOne.addEventListener('shown.bs.collapse', () => { + if (collapsedElements.one) { + firstTest() + } else { + collapsedElements.one = true + } + }) + + collapseOneTwo.addEventListener('shown.bs.collapse', () => { + if (collapsedElements.one) { + firstTest() + } else { + collapsedElements.one = true + } + }) + + collapseTwoOne.addEventListener('shown.bs.collapse', () => { + if (collapsedElements.two) { + secondTest() + } else { + collapsedElements.two = true + } + }) + + collapseTwoTwo.addEventListener('shown.bs.collapse', () => { + if (collapsedElements.two) { + secondTest() + } else { + collapsedElements.two = true + } + }) + + trigger.click() + }) + }) + + it('should collapse accordion children but not nested accordion children', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '
', + '
', + ' ', + '
', + '
', + '
', + ' ', + '
', + '
', + '
', + '
', + '
', + '
', + ' ', + '
', + '
', + '
' + ].join('') + + const trigger = fixtureEl.querySelector('#linkTrigger') + const triggerTwo = fixtureEl.querySelector('#linkTriggerTwo') + const nestedTrigger = fixtureEl.querySelector('#nestedLinkTrigger') + const collapseOne = fixtureEl.querySelector('#collapseOne') + const collapseTwo = fixtureEl.querySelector('#collapseTwo') + const nestedCollapseOne = fixtureEl.querySelector('#nestedCollapseOne') + + function handlerCollapseOne() { + expect(collapseOne).toHaveClass('show') + expect(collapseTwo).not.toHaveClass('show') + expect(nestedCollapseOne).not.toHaveClass('show') + + nestedCollapseOne.addEventListener('shown.bs.collapse', handlerNestedCollapseOne) + nestedTrigger.click() + collapseOne.removeEventListener('shown.bs.collapse', handlerCollapseOne) + } + + function handlerNestedCollapseOne() { + expect(collapseOne).toHaveClass('show') + expect(collapseTwo).not.toHaveClass('show') + expect(nestedCollapseOne).toHaveClass('show') + + collapseTwo.addEventListener('shown.bs.collapse', () => { + expect(collapseOne).not.toHaveClass('show') + expect(collapseTwo).toHaveClass('show') + expect(nestedCollapseOne).toHaveClass('show') + resolve() + }) + + triggerTwo.click() + nestedCollapseOne.removeEventListener('shown.bs.collapse', handlerNestedCollapseOne) + } + + collapseOne.addEventListener('shown.bs.collapse', handlerCollapseOne) + trigger.click() + }) + }) + + it('should add "collapsed" class and set aria-expanded to triggers only when all the targeted collapse are hidden', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '', + '', + '
', + '
' + ].join('') + + const trigger1 = fixtureEl.querySelector('#trigger1') + const trigger2 = fixtureEl.querySelector('#trigger2') + const trigger3 = fixtureEl.querySelector('#trigger3') + const target1 = fixtureEl.querySelector('#test1') + const target2 = fixtureEl.querySelector('#test2') + + const target2Shown = () => { + expect(trigger1).not.toHaveClass('collapsed') + expect(trigger1.getAttribute('aria-expanded')).toEqual('true') + + expect(trigger2).not.toHaveClass('collapsed') + expect(trigger2.getAttribute('aria-expanded')).toEqual('true') + + expect(trigger3).not.toHaveClass('collapsed') + expect(trigger3.getAttribute('aria-expanded')).toEqual('true') + + target2.addEventListener('hidden.bs.collapse', () => { + expect(trigger1).not.toHaveClass('collapsed') + expect(trigger1.getAttribute('aria-expanded')).toEqual('true') + + expect(trigger2).toHaveClass('collapsed') + expect(trigger2.getAttribute('aria-expanded')).toEqual('false') + + expect(trigger3).not.toHaveClass('collapsed') + expect(trigger3.getAttribute('aria-expanded')).toEqual('true') + + target1.addEventListener('hidden.bs.collapse', () => { + expect(trigger1).toHaveClass('collapsed') + expect(trigger1.getAttribute('aria-expanded')).toEqual('false') + + expect(trigger2).toHaveClass('collapsed') + expect(trigger2.getAttribute('aria-expanded')).toEqual('false') + + expect(trigger3).toHaveClass('collapsed') + expect(trigger3.getAttribute('aria-expanded')).toEqual('false') + resolve() + }) + + trigger1.click() + }) + + trigger2.click() + } + + target2.addEventListener('shown.bs.collapse', target2Shown) + trigger3.click() + }) + }) + }) + + describe('jQueryInterface', () => { + it('should create a collapse', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + jQueryMock.fn.collapse = Collapse.jQueryInterface + jQueryMock.elements = [div] + + jQueryMock.fn.collapse.call(jQueryMock) + + expect(Collapse.getInstance(div)).not.toBeNull() + }) + + it('should not re create a collapse', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const collapse = new Collapse(div) + + jQueryMock.fn.collapse = Collapse.jQueryInterface + jQueryMock.elements = [div] + + jQueryMock.fn.collapse.call(jQueryMock) + + expect(Collapse.getInstance(div)).toEqual(collapse) + }) + + it('should throw error on undefined method', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const action = 'undefinedMethod' + + jQueryMock.fn.collapse = Collapse.jQueryInterface + jQueryMock.elements = [div] + + expect(() => { + jQueryMock.fn.collapse.call(jQueryMock, action) + }).toThrowError(TypeError, `No method named "${action}"`) + }) + }) + + describe('getInstance', () => { + it('should return collapse instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const collapse = new Collapse(div) + + expect(Collapse.getInstance(div)).toEqual(collapse) + expect(Collapse.getInstance(div)).toBeInstanceOf(Collapse) + }) + + it('should return null when there is no collapse instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(Collapse.getInstance(div)).toBeNull() + }) + }) + + describe('getOrCreateInstance', () => { + it('should return collapse instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const collapse = new Collapse(div) + + expect(Collapse.getOrCreateInstance(div)).toEqual(collapse) + expect(Collapse.getInstance(div)).toEqual(Collapse.getOrCreateInstance(div, {})) + expect(Collapse.getOrCreateInstance(div)).toBeInstanceOf(Collapse) + }) + + it('should return new instance when there is no collapse instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(Collapse.getInstance(div)).toBeNull() + expect(Collapse.getOrCreateInstance(div)).toBeInstanceOf(Collapse) + }) + + it('should return new instance when there is no collapse instance with given configuration', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(Collapse.getInstance(div)).toBeNull() + const collapse = Collapse.getOrCreateInstance(div, { + toggle: false + }) + expect(collapse).toBeInstanceOf(Collapse) + + expect(collapse._config.toggle).toBeFalse() + }) + + it('should return the instance when exists without given configuration', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const collapse = new Collapse(div, { + toggle: false + }) + expect(Collapse.getInstance(div)).toEqual(collapse) + + const collapse2 = Collapse.getOrCreateInstance(div, { + toggle: true + }) + expect(collapse).toBeInstanceOf(Collapse) + expect(collapse2).toEqual(collapse) + + expect(collapse2._config.toggle).toBeFalse() + }) + }) +}) diff --git a/js/tests/unit/dom/data.spec.js b/js/tests/unit/dom/data.spec.js new file mode 100644 index 0000000..e898cbb --- /dev/null +++ b/js/tests/unit/dom/data.spec.js @@ -0,0 +1,106 @@ +import Data from '../../../src/dom/data' +import { getFixture, clearFixture } from '../../helpers/fixture' + +describe('Data', () => { + const TEST_KEY = 'bs.test' + const UNKNOWN_KEY = 'bs.unknown' + const TEST_DATA = { + test: 'bsData' + } + + let fixtureEl + let div + + beforeAll(() => { + fixtureEl = getFixture() + }) + + beforeEach(() => { + fixtureEl.innerHTML = '
' + div = fixtureEl.querySelector('div') + }) + + afterEach(() => { + Data.remove(div, TEST_KEY) + clearFixture() + }) + + it('should return null for unknown elements', () => { + const data = { ...TEST_DATA } + + Data.set(div, TEST_KEY, data) + + expect(Data.get(null)).toBeNull() + expect(Data.get(undefined)).toBeNull() + expect(Data.get(document.createElement('div'), TEST_KEY)).toBeNull() + }) + + it('should return null for unknown keys', () => { + const data = { ...TEST_DATA } + + Data.set(div, TEST_KEY, data) + + expect(Data.get(div, null)).toBeNull() + expect(Data.get(div, undefined)).toBeNull() + expect(Data.get(div, UNKNOWN_KEY)).toBeNull() + }) + + it('should store data for an element with a given key and return it', () => { + const data = { ...TEST_DATA } + + Data.set(div, TEST_KEY, data) + + expect(Data.get(div, TEST_KEY)).toEqual(data) + }) + + it('should overwrite data if something is already stored', () => { + const data = { ...TEST_DATA } + const copy = { ...data } + + Data.set(div, TEST_KEY, data) + Data.set(div, TEST_KEY, copy) + + // Using `toBe` since spread creates a shallow copy + expect(Data.get(div, TEST_KEY)).not.toBe(data) + expect(Data.get(div, TEST_KEY)).toBe(copy) + }) + + it('should do nothing when an element has nothing stored', () => { + Data.remove(div, TEST_KEY) + + expect().nothing() + }) + + it('should remove nothing for an unknown key', () => { + const data = { ...TEST_DATA } + + Data.set(div, TEST_KEY, data) + Data.remove(div, UNKNOWN_KEY) + + expect(Data.get(div, TEST_KEY)).toEqual(data) + }) + + it('should remove data for a given key', () => { + const data = { ...TEST_DATA } + + Data.set(div, TEST_KEY, data) + Data.remove(div, TEST_KEY) + + expect(Data.get(div, TEST_KEY)).toBeNull() + }) + + /* eslint-disable no-console */ + it('should console.error a message if called with multiple keys', () => { + console.error = jasmine.createSpy('console.error') + + const data = { ...TEST_DATA } + const copy = { ...data } + + Data.set(div, TEST_KEY, data) + Data.set(div, UNKNOWN_KEY, copy) + + expect(console.error).toHaveBeenCalled() + expect(Data.get(div, UNKNOWN_KEY)).toBeNull() + }) + /* eslint-enable no-console */ +}) diff --git a/js/tests/unit/dom/event-handler.spec.js b/js/tests/unit/dom/event-handler.spec.js new file mode 100644 index 0000000..623b9c1 --- /dev/null +++ b/js/tests/unit/dom/event-handler.spec.js @@ -0,0 +1,480 @@ +import EventHandler from '../../../src/dom/event-handler' +import { clearFixture, getFixture } from '../../helpers/fixture' +import { noop } from '../../../src/util' + +describe('EventHandler', () => { + let fixtureEl + + beforeAll(() => { + fixtureEl = getFixture() + }) + + afterEach(() => { + clearFixture() + }) + + describe('on', () => { + it('should not add event listener if the event is not a string', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + EventHandler.on(div, null, noop) + EventHandler.on(null, 'click', noop) + + expect().nothing() + }) + + it('should add event listener', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + EventHandler.on(div, 'click', () => { + expect().nothing() + resolve() + }) + + div.click() + }) + }) + + it('should add namespaced event listener', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + EventHandler.on(div, 'bs.namespace', () => { + expect().nothing() + resolve() + }) + + EventHandler.trigger(div, 'bs.namespace') + }) + }) + + it('should add native namespaced event listener', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + EventHandler.on(div, 'click.namespace', () => { + expect().nothing() + resolve() + }) + + EventHandler.trigger(div, 'click') + }) + }) + + it('should handle event delegation', () => { + return new Promise(resolve => { + EventHandler.on(document, 'click', '.test', () => { + expect().nothing() + resolve() + }) + + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + div.click() + }) + }) + + it('should handle mouseenter/mouseleave like the native counterpart', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '
', + '
', + '
', + '
', + '
', + '
', + '
', + '
' + ].join('') + + const outer = fixtureEl.querySelector('.outer') + const inner = fixtureEl.querySelector('.inner') + const nested = fixtureEl.querySelector('.nested') + const deep = fixtureEl.querySelector('.deep') + const sibling = fixtureEl.querySelector('.sibling') + + const enterSpy = jasmine.createSpy('mouseenter') + const leaveSpy = jasmine.createSpy('mouseleave') + const delegateEnterSpy = jasmine.createSpy('mouseenter') + const delegateLeaveSpy = jasmine.createSpy('mouseleave') + + EventHandler.on(inner, 'mouseenter', enterSpy) + EventHandler.on(inner, 'mouseleave', leaveSpy) + EventHandler.on(outer, 'mouseenter', '.inner', delegateEnterSpy) + EventHandler.on(outer, 'mouseleave', '.inner', delegateLeaveSpy) + + EventHandler.on(sibling, 'mouseenter', () => { + expect(enterSpy.calls.count()).toEqual(2) + expect(leaveSpy.calls.count()).toEqual(2) + expect(delegateEnterSpy.calls.count()).toEqual(2) + expect(delegateLeaveSpy.calls.count()).toEqual(2) + resolve() + }) + + const moveMouse = (from, to) => { + from.dispatchEvent(new MouseEvent('mouseout', { + bubbles: true, + relatedTarget: to + })) + + to.dispatchEvent(new MouseEvent('mouseover', { + bubbles: true, + relatedTarget: from + })) + } + + // from outer to deep and back to outer (nested) + moveMouse(outer, inner) + moveMouse(inner, nested) + moveMouse(nested, deep) + moveMouse(deep, nested) + moveMouse(nested, inner) + moveMouse(inner, outer) + + setTimeout(() => { + expect(enterSpy.calls.count()).toEqual(1) + expect(leaveSpy.calls.count()).toEqual(1) + expect(delegateEnterSpy.calls.count()).toEqual(1) + expect(delegateLeaveSpy.calls.count()).toEqual(1) + + // from outer to inner to sibling (adjacent) + moveMouse(outer, inner) + moveMouse(inner, sibling) + }, 20) + }) + }) + }) + + describe('one', () => { + it('should call listener just once', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + + let called = 0 + const div = fixtureEl.querySelector('div') + const obj = { + oneListener() { + called++ + } + } + + EventHandler.one(div, 'bootstrap', obj.oneListener) + + EventHandler.trigger(div, 'bootstrap') + EventHandler.trigger(div, 'bootstrap') + + setTimeout(() => { + expect(called).toEqual(1) + resolve() + }, 20) + }) + }) + + it('should call delegated listener just once', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + + let called = 0 + const div = fixtureEl.querySelector('div') + const obj = { + oneListener() { + called++ + } + } + + EventHandler.one(fixtureEl, 'bootstrap', 'div', obj.oneListener) + + EventHandler.trigger(div, 'bootstrap') + EventHandler.trigger(div, 'bootstrap') + + setTimeout(() => { + expect(called).toEqual(1) + resolve() + }, 20) + }) + }) + }) + + describe('off', () => { + it('should not remove a listener', () => { + fixtureEl.innerHTML = '
' + const div = fixtureEl.querySelector('div') + + EventHandler.off(div, null, noop) + EventHandler.off(null, 'click', noop) + expect().nothing() + }) + + it('should remove a listener', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + const div = fixtureEl.querySelector('div') + + let called = 0 + const handler = () => { + called++ + } + + EventHandler.on(div, 'foobar', handler) + EventHandler.trigger(div, 'foobar') + + EventHandler.off(div, 'foobar', handler) + EventHandler.trigger(div, 'foobar') + + setTimeout(() => { + expect(called).toEqual(1) + resolve() + }, 20) + }) + }) + + it('should remove all the events', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + const div = fixtureEl.querySelector('div') + + let called = 0 + + EventHandler.on(div, 'foobar', () => { + called++ + }) + EventHandler.on(div, 'foobar', () => { + called++ + }) + EventHandler.trigger(div, 'foobar') + + EventHandler.off(div, 'foobar') + EventHandler.trigger(div, 'foobar') + + setTimeout(() => { + expect(called).toEqual(2) + resolve() + }, 20) + }) + }) + + it('should remove all the namespaced listeners if namespace is passed', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + const div = fixtureEl.querySelector('div') + + let called = 0 + + EventHandler.on(div, 'foobar.namespace', () => { + called++ + }) + EventHandler.on(div, 'foofoo.namespace', () => { + called++ + }) + EventHandler.trigger(div, 'foobar.namespace') + EventHandler.trigger(div, 'foofoo.namespace') + + EventHandler.off(div, '.namespace') + EventHandler.trigger(div, 'foobar.namespace') + EventHandler.trigger(div, 'foofoo.namespace') + + setTimeout(() => { + expect(called).toEqual(2) + resolve() + }, 20) + }) + }) + + it('should remove the namespaced listeners', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + const div = fixtureEl.querySelector('div') + + let calledCallback1 = 0 + let calledCallback2 = 0 + + EventHandler.on(div, 'foobar.namespace', () => { + calledCallback1++ + }) + EventHandler.on(div, 'foofoo.namespace', () => { + calledCallback2++ + }) + + EventHandler.trigger(div, 'foobar.namespace') + EventHandler.off(div, 'foobar.namespace') + EventHandler.trigger(div, 'foobar.namespace') + + EventHandler.trigger(div, 'foofoo.namespace') + + setTimeout(() => { + expect(calledCallback1).toEqual(1) + expect(calledCallback2).toEqual(1) + resolve() + }, 20) + }) + }) + + it('should remove the all the namespaced listeners for native events', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + const div = fixtureEl.querySelector('div') + + let called = 0 + + EventHandler.on(div, 'click.namespace', () => { + called++ + }) + EventHandler.on(div, 'click.namespace2', () => { + called++ + }) + + EventHandler.trigger(div, 'click') + EventHandler.off(div, 'click') + EventHandler.trigger(div, 'click') + + setTimeout(() => { + expect(called).toEqual(2) + resolve() + }, 20) + }) + }) + + it('should remove the specified namespaced listeners for native events', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + const div = fixtureEl.querySelector('div') + + let called1 = 0 + let called2 = 0 + + EventHandler.on(div, 'click.namespace', () => { + called1++ + }) + EventHandler.on(div, 'click.namespace2', () => { + called2++ + }) + EventHandler.trigger(div, 'click') + + EventHandler.off(div, 'click.namespace') + EventHandler.trigger(div, 'click') + + setTimeout(() => { + expect(called1).toEqual(1) + expect(called2).toEqual(2) + resolve() + }, 20) + }) + }) + + it('should remove a listener registered by .one', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const handler = () => { + reject(new Error('called')) + } + + EventHandler.one(div, 'foobar', handler) + EventHandler.off(div, 'foobar', handler) + + EventHandler.trigger(div, 'foobar') + setTimeout(() => { + expect().nothing() + resolve() + }, 20) + }) + }) + + it('should remove the correct delegated event listener', () => { + const element = document.createElement('div') + const subelement = document.createElement('span') + element.append(subelement) + + const anchor = document.createElement('a') + element.append(anchor) + + let i = 0 + const handler = () => { + i++ + } + + EventHandler.on(element, 'click', 'a', handler) + EventHandler.on(element, 'click', 'span', handler) + + fixtureEl.append(element) + + EventHandler.trigger(anchor, 'click') + EventHandler.trigger(subelement, 'click') + + // first listeners called + expect(i).toEqual(2) + + EventHandler.off(element, 'click', 'span', handler) + EventHandler.trigger(subelement, 'click') + + // removed listener not called + expect(i).toEqual(2) + + EventHandler.trigger(anchor, 'click') + + // not removed listener called + expect(i).toEqual(3) + + EventHandler.on(element, 'click', 'span', handler) + EventHandler.trigger(anchor, 'click') + EventHandler.trigger(subelement, 'click') + + // listener re-registered + expect(i).toEqual(5) + + EventHandler.off(element, 'click', 'span') + EventHandler.trigger(subelement, 'click') + + // listener removed again + expect(i).toEqual(5) + }) + }) + + describe('general functionality', () => { + it('should hydrate properties, and make them configurable', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '
', + '
', + '
', + '
' + ].join('') + + const div1 = fixtureEl.querySelector('#div1') + const div2 = fixtureEl.querySelector('#div2') + + EventHandler.on(div1, 'click', event => { + expect(event.currentTarget).toBe(div2) + expect(event.delegateTarget).toBe(div1) + expect(event.originalTarget).toBeNull() + + Object.defineProperty(event, 'currentTarget', { + configurable: true, + get() { + return div1 + } + }) + + expect(event.currentTarget).toBe(div1) + resolve() + }) + + expect(() => { + EventHandler.trigger(div1, 'click', { originalTarget: null, currentTarget: div2 }) + }).not.toThrowError(TypeError) + }) + }) + }) +}) diff --git a/js/tests/unit/dom/manipulator.spec.js b/js/tests/unit/dom/manipulator.spec.js new file mode 100644 index 0000000..4561e2e --- /dev/null +++ b/js/tests/unit/dom/manipulator.spec.js @@ -0,0 +1,135 @@ +import Manipulator from '../../../src/dom/manipulator' +import { clearFixture, getFixture } from '../../helpers/fixture' + +describe('Manipulator', () => { + let fixtureEl + + beforeAll(() => { + fixtureEl = getFixture() + }) + + afterEach(() => { + clearFixture() + }) + + describe('setDataAttribute', () => { + it('should set data attribute prefixed with bs', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + Manipulator.setDataAttribute(div, 'key', 'value') + expect(div.getAttribute('data-bs-key')).toEqual('value') + }) + + it('should set data attribute in kebab case', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + Manipulator.setDataAttribute(div, 'testKey', 'value') + expect(div.getAttribute('data-bs-test-key')).toEqual('value') + }) + }) + + describe('removeDataAttribute', () => { + it('should only remove bs-prefixed data attribute', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + Manipulator.removeDataAttribute(div, 'key') + expect(div.getAttribute('data-bs-key')).toBeNull() + expect(div.getAttribute('data-key-bs')).toEqual('postfixed') + expect(div.getAttribute('data-key')).toEqual('value') + }) + + it('should remove data attribute in kebab case', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + Manipulator.removeDataAttribute(div, 'testKey') + expect(div.getAttribute('data-bs-test-key')).toBeNull() + }) + }) + + describe('getDataAttributes', () => { + it('should return an empty object for null', () => { + expect(Manipulator.getDataAttributes(null)).toEqual({}) + expect().nothing() + }) + + it('should get only bs-prefixed data attributes without bs namespace', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(Manipulator.getDataAttributes(div)).toEqual({ + toggle: 'tabs', + target: '#element' + }) + }) + + it('should omit `bs-config` data attribute', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(Manipulator.getDataAttributes(div)).toEqual({ + toggle: 'tabs', + target: '#element' + }) + }) + }) + + describe('getDataAttribute', () => { + it('should only get bs-prefixed data attribute', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(Manipulator.getDataAttribute(div, 'key')).toEqual('value') + expect(Manipulator.getDataAttribute(div, 'test')).toBeNull() + expect(Manipulator.getDataAttribute(div, 'toggle')).toBeNull() + }) + + it('should get data attribute in kebab case', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(Manipulator.getDataAttribute(div, 'testKey')).toEqual('value') + }) + + it('should normalize data', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(Manipulator.getDataAttribute(div, 'test')).toBeFalse() + + div.setAttribute('data-bs-test', 'true') + expect(Manipulator.getDataAttribute(div, 'test')).toBeTrue() + + div.setAttribute('data-bs-test', '1') + expect(Manipulator.getDataAttribute(div, 'test')).toEqual(1) + }) + + it('should normalize json data', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(Manipulator.getDataAttribute(div, 'test')).toEqual({ delay: { show: 100, hide: 10 } }) + + const objectData = { 'Super Hero': ['Iron Man', 'Super Man'], testNum: 90, url: 'http://localhost:8080/test?foo=bar' } + const dataStr = JSON.stringify(objectData) + div.setAttribute('data-bs-test', encodeURIComponent(dataStr)) + expect(Manipulator.getDataAttribute(div, 'test')).toEqual(objectData) + + div.setAttribute('data-bs-test', dataStr) + expect(Manipulator.getDataAttribute(div, 'test')).toEqual(objectData) + }) + }) +}) diff --git a/js/tests/unit/dom/selector-engine.spec.js b/js/tests/unit/dom/selector-engine.spec.js new file mode 100644 index 0000000..0245896 --- /dev/null +++ b/js/tests/unit/dom/selector-engine.spec.js @@ -0,0 +1,236 @@ +import SelectorEngine from '../../../src/dom/selector-engine' +import { getFixture, clearFixture } from '../../helpers/fixture' + +describe('SelectorEngine', () => { + let fixtureEl + + beforeAll(() => { + fixtureEl = getFixture() + }) + + afterEach(() => { + clearFixture() + }) + + describe('find', () => { + it('should find elements', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(SelectorEngine.find('div', fixtureEl)).toEqual([div]) + }) + + it('should find elements globally', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('#test') + + expect(SelectorEngine.find('#test')).toEqual([div]) + }) + + it('should handle :scope selectors', () => { + fixtureEl.innerHTML = [ + '
    ', + '
  • ', + '
  • ', + ' link', + '
  • ', + '
  • ', + '
' + ].join('') + + const listEl = fixtureEl.querySelector('ul') + const aActive = fixtureEl.querySelector('.active') + + expect(SelectorEngine.find(':scope > li > .active', listEl)).toEqual([aActive]) + }) + }) + + describe('findOne', () => { + it('should return one element', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('#test') + + expect(SelectorEngine.findOne('#test')).toEqual(div) + }) + }) + + describe('children', () => { + it('should find children', () => { + fixtureEl.innerHTML = [ + '
    ', + '
  • ', + '
  • ', + '
  • ', + '
' + ].join('') + + const list = fixtureEl.querySelector('ul') + const liList = [].concat(...fixtureEl.querySelectorAll('li')) + const result = SelectorEngine.children(list, 'li') + + expect(result).toEqual(liList) + }) + }) + + describe('parents', () => { + it('should return parents', () => { + expect(SelectorEngine.parents(fixtureEl, 'body')).toHaveSize(1) + }) + }) + + describe('prev', () => { + it('should return previous element', () => { + fixtureEl.innerHTML = '
' + + const btn = fixtureEl.querySelector('.btn') + const divTest = fixtureEl.querySelector('.test') + + expect(SelectorEngine.prev(btn, '.test')).toEqual([divTest]) + }) + + it('should return previous element with an extra element between', () => { + fixtureEl.innerHTML = [ + '
', + '', + '' + ].join('') + + const btn = fixtureEl.querySelector('.btn') + const divTest = fixtureEl.querySelector('.test') + + expect(SelectorEngine.prev(btn, '.test')).toEqual([divTest]) + }) + + it('should return previous element with comments or text nodes between', () => { + fixtureEl.innerHTML = [ + '
', + '
', + '', + 'Text', + '' + ].join('') + + const btn = fixtureEl.querySelector('.btn') + const divTest = fixtureEl.querySelectorAll('.test')[1] + + expect(SelectorEngine.prev(btn, '.test')).toEqual([divTest]) + }) + }) + + describe('next', () => { + it('should return next element', () => { + fixtureEl.innerHTML = '
' + + const btn = fixtureEl.querySelector('.btn') + const divTest = fixtureEl.querySelector('.test') + + expect(SelectorEngine.next(divTest, '.btn')).toEqual([btn]) + }) + + it('should return next element with an extra element between', () => { + fixtureEl.innerHTML = [ + '
', + '', + '' + ].join('') + + const btn = fixtureEl.querySelector('.btn') + const divTest = fixtureEl.querySelector('.test') + + expect(SelectorEngine.next(divTest, '.btn')).toEqual([btn]) + }) + + it('should return next element with comments or text nodes between', () => { + fixtureEl.innerHTML = [ + '
', + '', + 'Text', + '', + '' + ].join('') + + const btn = fixtureEl.querySelector('.btn') + const divTest = fixtureEl.querySelector('.test') + + expect(SelectorEngine.next(divTest, '.btn')).toEqual([btn]) + }) + }) + + describe('focusableChildren', () => { + it('should return only elements with specific tag names', () => { + fixtureEl.innerHTML = [ + '
lorem
', + 'lorem', + 'lorem', + '', + '', + '', + '', + '
lorem
' + ].join('') + + const expectedElements = [ + fixtureEl.querySelector('a'), + fixtureEl.querySelector('button'), + fixtureEl.querySelector('input'), + fixtureEl.querySelector('textarea'), + fixtureEl.querySelector('select'), + fixtureEl.querySelector('details') + ] + + expect(SelectorEngine.focusableChildren(fixtureEl)).toEqual(expectedElements) + }) + + it('should return any element with non negative tab index', () => { + fixtureEl.innerHTML = [ + '
lorem
', + '
lorem
', + '
lorem
' + ].join('') + + const expectedElements = [ + fixtureEl.querySelector('[tabindex]'), + fixtureEl.querySelector('[tabindex="0"]'), + fixtureEl.querySelector('[tabindex="10"]') + ] + + expect(SelectorEngine.focusableChildren(fixtureEl)).toEqual(expectedElements) + }) + + it('should return not return elements with negative tab index', () => { + fixtureEl.innerHTML = '' + + const expectedElements = [] + + expect(SelectorEngine.focusableChildren(fixtureEl)).toEqual(expectedElements) + }) + + it('should return contenteditable elements', () => { + fixtureEl.innerHTML = '
lorem
' + + const expectedElements = [fixtureEl.querySelector('[contenteditable="true"]')] + + expect(SelectorEngine.focusableChildren(fixtureEl)).toEqual(expectedElements) + }) + + it('should not return disabled elements', () => { + fixtureEl.innerHTML = '' + + const expectedElements = [] + + expect(SelectorEngine.focusableChildren(fixtureEl)).toEqual(expectedElements) + }) + + it('should not return invisible elements', () => { + fixtureEl.innerHTML = '' + + const expectedElements = [] + + expect(SelectorEngine.focusableChildren(fixtureEl)).toEqual(expectedElements) + }) + }) +}) + diff --git a/js/tests/unit/dropdown.spec.js b/js/tests/unit/dropdown.spec.js new file mode 100644 index 0000000..2bbd7c0 --- /dev/null +++ b/js/tests/unit/dropdown.spec.js @@ -0,0 +1,2430 @@ +import Dropdown from '../../src/dropdown' +import EventHandler from '../../src/dom/event-handler' +import { noop } from '../../src/util/index' +import { clearFixture, createEvent, getFixture, jQueryMock } from '../helpers/fixture' + +describe('Dropdown', () => { + let fixtureEl + + beforeAll(() => { + fixtureEl = getFixture() + }) + + afterEach(() => { + clearFixture() + }) + + describe('VERSION', () => { + it('should return plugin version', () => { + expect(Dropdown.VERSION).toEqual(jasmine.any(String)) + }) + }) + + describe('Default', () => { + it('should return plugin default config', () => { + expect(Dropdown.Default).toEqual(jasmine.any(Object)) + }) + }) + + describe('DefaultType', () => { + it('should return plugin default type config', () => { + expect(Dropdown.DefaultType).toEqual(jasmine.any(Object)) + }) + }) + + describe('DATA_KEY', () => { + it('should return plugin data key', () => { + expect(Dropdown.DATA_KEY).toEqual('bs.dropdown') + }) + }) + + describe('constructor', () => { + it('should take care of element either passed as a CSS selector or DOM element', () => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdownBySelector = new Dropdown('[data-bs-toggle="dropdown"]') + const dropdownByElement = new Dropdown(btnDropdown) + + expect(dropdownBySelector._element).toEqual(btnDropdown) + expect(dropdownByElement._element).toEqual(btnDropdown) + }) + + it('should work on invalid markup', () => { + return new Promise(resolve => { + // TODO: REMOVE in v6 + fixtureEl.innerHTML = [ + '' + ].join('') + + const dropdownElem = fixtureEl.querySelector('.dropdown-menu') + const dropdown = new Dropdown(dropdownElem) + + dropdownElem.addEventListener('shown.bs.dropdown', () => { + resolve() + }) + + dropdown.show() + }) + }) + + it('should create offset modifier correctly when offset option is a function', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const getOffset = jasmine.createSpy('getOffset').and.returnValue([10, 20]) + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdown = new Dropdown(btnDropdown, { + offset: getOffset, + popperConfig: { + onFirstUpdate(state) { + expect(getOffset).toHaveBeenCalledWith({ + popper: state.rects.popper, + reference: state.rects.reference, + placement: state.placement + }, btnDropdown) + resolve() + } + } + }) + const offset = dropdown._getOffset() + + expect(typeof offset).toEqual('function') + + dropdown.show() + }) + }) + + it('should create offset modifier correctly when offset option is a string into data attribute', () => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdown = new Dropdown(btnDropdown) + + expect(dropdown._getOffset()).toEqual([10, 20]) + }) + + it('should allow to pass config to Popper with `popperConfig`', () => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdown = new Dropdown(btnDropdown, { + popperConfig: { + placement: 'left' + } + }) + + const popperConfig = dropdown._getPopperConfig() + + expect(popperConfig.placement).toEqual('left') + }) + + it('should allow to pass config to Popper with `popperConfig` as a function', () => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const getPopperConfig = jasmine.createSpy('getPopperConfig').and.returnValue({ placement: 'left' }) + const dropdown = new Dropdown(btnDropdown, { + popperConfig: getPopperConfig + }) + + const popperConfig = dropdown._getPopperConfig() + + expect(getPopperConfig).toHaveBeenCalled() + expect(popperConfig.placement).toEqual('left') + }) + }) + + describe('toggle', () => { + it('should toggle a dropdown', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdown = new Dropdown(btnDropdown) + + btnDropdown.addEventListener('shown.bs.dropdown', () => { + expect(btnDropdown).toHaveClass('show') + expect(btnDropdown.getAttribute('aria-expanded')).toEqual('true') + resolve() + }) + + dropdown.toggle() + }) + }) + + it('should destroy old popper references on toggle', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '' + ].join('') + + const btnDropdown1 = fixtureEl.querySelector('.firstBtn') + const btnDropdown2 = fixtureEl.querySelector('.secondBtn') + const firstDropdownEl = fixtureEl.querySelector('.first') + const secondDropdownEl = fixtureEl.querySelector('.second') + const dropdown1 = new Dropdown(btnDropdown1) + + firstDropdownEl.addEventListener('shown.bs.dropdown', () => { + expect(btnDropdown1).toHaveClass('show') + spyOn(dropdown1._popper, 'destroy') + btnDropdown2.click() + }) + + secondDropdownEl.addEventListener('shown.bs.dropdown', () => setTimeout(() => { + expect(dropdown1._popper.destroy).toHaveBeenCalled() + resolve() + })) + + dropdown1.toggle() + }) + }) + + it('should toggle a dropdown and add/remove event listener on mobile', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const defaultValueOnTouchStart = document.documentElement.ontouchstart + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdown = new Dropdown(btnDropdown) + + document.documentElement.ontouchstart = noop + const spy = spyOn(EventHandler, 'on') + const spyOff = spyOn(EventHandler, 'off') + + btnDropdown.addEventListener('shown.bs.dropdown', () => { + expect(btnDropdown).toHaveClass('show') + expect(btnDropdown.getAttribute('aria-expanded')).toEqual('true') + expect(spy).toHaveBeenCalledWith(jasmine.any(Object), 'mouseover', noop) + + dropdown.toggle() + }) + + btnDropdown.addEventListener('hidden.bs.dropdown', () => { + expect(btnDropdown).not.toHaveClass('show') + expect(btnDropdown.getAttribute('aria-expanded')).toEqual('false') + expect(spyOff).toHaveBeenCalledWith(jasmine.any(Object), 'mouseover', noop) + + document.documentElement.ontouchstart = defaultValueOnTouchStart + resolve() + }) + + dropdown.toggle() + }) + }) + + it('should toggle a dropdown at the right', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdown = new Dropdown(btnDropdown) + + btnDropdown.addEventListener('shown.bs.dropdown', () => { + expect(btnDropdown).toHaveClass('show') + expect(btnDropdown.getAttribute('aria-expanded')).toEqual('true') + resolve() + }) + + dropdown.toggle() + }) + }) + + it('should toggle a centered dropdown', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdown = new Dropdown(btnDropdown) + + btnDropdown.addEventListener('shown.bs.dropdown', () => { + expect(btnDropdown).toHaveClass('show') + expect(btnDropdown.getAttribute('aria-expanded')).toEqual('true') + resolve() + }) + + dropdown.toggle() + }) + }) + + it('should toggle a dropup', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '
', + ' ', + ' ', + '
' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropupEl = fixtureEl.querySelector('.dropup') + const dropdown = new Dropdown(btnDropdown) + + dropupEl.addEventListener('shown.bs.dropdown', () => { + expect(btnDropdown).toHaveClass('show') + expect(btnDropdown.getAttribute('aria-expanded')).toEqual('true') + resolve() + }) + + dropdown.toggle() + }) + }) + + it('should toggle a dropup centered', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '
', + ' ', + ' ', + '
' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropupEl = fixtureEl.querySelector('.dropup-center') + const dropdown = new Dropdown(btnDropdown) + + dropupEl.addEventListener('shown.bs.dropdown', () => { + expect(btnDropdown).toHaveClass('show') + expect(btnDropdown.getAttribute('aria-expanded')).toEqual('true') + resolve() + }) + + dropdown.toggle() + }) + }) + + it('should toggle a dropup at the right', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '
', + ' ', + ' ', + '
' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropupEl = fixtureEl.querySelector('.dropup') + const dropdown = new Dropdown(btnDropdown) + + dropupEl.addEventListener('shown.bs.dropdown', () => { + expect(btnDropdown).toHaveClass('show') + expect(btnDropdown.getAttribute('aria-expanded')).toEqual('true') + resolve() + }) + + dropdown.toggle() + }) + }) + + it('should toggle a dropend', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '
', + ' ', + ' ', + '
' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropendEl = fixtureEl.querySelector('.dropend') + const dropdown = new Dropdown(btnDropdown) + + dropendEl.addEventListener('shown.bs.dropdown', () => { + expect(btnDropdown).toHaveClass('show') + expect(btnDropdown.getAttribute('aria-expanded')).toEqual('true') + resolve() + }) + + dropdown.toggle() + }) + }) + + it('should toggle a dropstart', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '
', + ' ', + ' ', + '
' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropstartEl = fixtureEl.querySelector('.dropstart') + const dropdown = new Dropdown(btnDropdown) + + dropstartEl.addEventListener('shown.bs.dropdown', () => { + expect(btnDropdown).toHaveClass('show') + expect(btnDropdown.getAttribute('aria-expanded')).toEqual('true') + resolve() + }) + + dropdown.toggle() + }) + }) + + it('should toggle a dropdown with parent reference', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdown = new Dropdown(btnDropdown, { + reference: 'parent' + }) + + btnDropdown.addEventListener('shown.bs.dropdown', () => { + expect(btnDropdown).toHaveClass('show') + expect(btnDropdown.getAttribute('aria-expanded')).toEqual('true') + resolve() + }) + + dropdown.toggle() + }) + }) + + it('should toggle a dropdown with a dom node reference', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdown = new Dropdown(btnDropdown, { + reference: fixtureEl + }) + + btnDropdown.addEventListener('shown.bs.dropdown', () => { + expect(btnDropdown).toHaveClass('show') + expect(btnDropdown.getAttribute('aria-expanded')).toEqual('true') + resolve() + }) + + dropdown.toggle() + }) + }) + + it('should toggle a dropdown with a jquery object reference', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdown = new Dropdown(btnDropdown, { + reference: { 0: fixtureEl, jquery: 'jQuery' } + }) + + btnDropdown.addEventListener('shown.bs.dropdown', () => { + expect(btnDropdown).toHaveClass('show') + expect(btnDropdown.getAttribute('aria-expanded')).toEqual('true') + resolve() + }) + + dropdown.toggle() + }) + }) + + it('should toggle a dropdown with a valid virtual element reference', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const virtualElement = { + nodeType: 1, + getBoundingClientRect() { + return { + width: 0, + height: 0, + top: 0, + right: 0, + bottom: 0, + left: 0 + } + } + } + + expect(() => new Dropdown(btnDropdown, { + reference: {} + })).toThrowError(TypeError, 'DROPDOWN: Option "reference" provided type "object" without a required "getBoundingClientRect" method.') + + expect(() => new Dropdown(btnDropdown, { + reference: { + getBoundingClientRect: 'not-a-function' + } + })).toThrowError(TypeError, 'DROPDOWN: Option "reference" provided type "object" without a required "getBoundingClientRect" method.') + + // use onFirstUpdate as Poppers internal update is executed async + const dropdown = new Dropdown(btnDropdown, { + reference: virtualElement, + popperConfig: { + onFirstUpdate() { + expect(spy).toHaveBeenCalled() + expect(btnDropdown).toHaveClass('show') + expect(btnDropdown.getAttribute('aria-expanded')).toEqual('true') + resolve() + } + } + }) + + const spy = spyOn(virtualElement, 'getBoundingClientRect').and.callThrough() + + dropdown.toggle() + }) + }) + + it('should not toggle a dropdown if the element is disabled', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdown = new Dropdown(btnDropdown) + + btnDropdown.addEventListener('shown.bs.dropdown', () => { + reject(new Error('should not throw shown.bs.dropdown event')) + }) + + dropdown.toggle() + + setTimeout(() => { + expect().nothing() + resolve() + }) + }) + }) + + it('should not toggle a dropdown if the element contains .disabled', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdown = new Dropdown(btnDropdown) + + btnDropdown.addEventListener('shown.bs.dropdown', () => { + reject(new Error('should not throw shown.bs.dropdown event')) + }) + + dropdown.toggle() + + setTimeout(() => { + expect().nothing() + resolve() + }) + }) + }) + + it('should not toggle a dropdown if the menu is shown', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdown = new Dropdown(btnDropdown) + + btnDropdown.addEventListener('shown.bs.dropdown', () => { + reject(new Error('should not throw shown.bs.dropdown event')) + }) + + dropdown.toggle() + + setTimeout(() => { + expect().nothing() + resolve() + }) + }) + }) + + it('should not toggle a dropdown if show event is prevented', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdown = new Dropdown(btnDropdown) + + btnDropdown.addEventListener('show.bs.dropdown', event => { + event.preventDefault() + }) + + btnDropdown.addEventListener('shown.bs.dropdown', () => { + reject(new Error('should not throw shown.bs.dropdown event')) + }) + + dropdown.toggle() + + setTimeout(() => { + expect().nothing() + resolve() + }) + }) + }) + }) + + describe('show', () => { + it('should show a dropdown', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdown = new Dropdown(btnDropdown) + + btnDropdown.addEventListener('shown.bs.dropdown', () => { + expect(btnDropdown).toHaveClass('show') + resolve() + }) + + dropdown.show() + }) + }) + + it('should not show a dropdown if the element is disabled', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdown = new Dropdown(btnDropdown) + + btnDropdown.addEventListener('shown.bs.dropdown', () => { + reject(new Error('should not throw shown.bs.dropdown event')) + }) + + dropdown.show() + + setTimeout(() => { + expect().nothing() + resolve() + }, 10) + }) + }) + + it('should not show a dropdown if the element contains .disabled', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdown = new Dropdown(btnDropdown) + + btnDropdown.addEventListener('shown.bs.dropdown', () => { + reject(new Error('should not throw shown.bs.dropdown event')) + }) + + dropdown.show() + + setTimeout(() => { + expect().nothing() + resolve() + }, 10) + }) + }) + + it('should not show a dropdown if the menu is shown', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdown = new Dropdown(btnDropdown) + + btnDropdown.addEventListener('shown.bs.dropdown', () => { + reject(new Error('should not throw shown.bs.dropdown event')) + }) + + dropdown.show() + + setTimeout(() => { + expect().nothing() + resolve() + }, 10) + }) + }) + + it('should not show a dropdown if show event is prevented', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdown = new Dropdown(btnDropdown) + + btnDropdown.addEventListener('show.bs.dropdown', event => { + event.preventDefault() + }) + + btnDropdown.addEventListener('shown.bs.dropdown', () => { + reject(new Error('should not throw shown.bs.dropdown event')) + }) + + dropdown.show() + + setTimeout(() => { + expect().nothing() + resolve() + }, 10) + }) + }) + }) + + describe('hide', () => { + it('should hide a dropdown', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdownMenu = fixtureEl.querySelector('.dropdown-menu') + const dropdown = new Dropdown(btnDropdown) + + btnDropdown.addEventListener('hidden.bs.dropdown', () => { + expect(dropdownMenu).not.toHaveClass('show') + expect(btnDropdown.getAttribute('aria-expanded')).toEqual('false') + resolve() + }) + + dropdown.hide() + }) + }) + + it('should hide a dropdown and destroy popper', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdown = new Dropdown(btnDropdown) + + btnDropdown.addEventListener('shown.bs.dropdown', () => { + spyOn(dropdown._popper, 'destroy') + dropdown.hide() + }) + + btnDropdown.addEventListener('hidden.bs.dropdown', () => { + expect(dropdown._popper.destroy).toHaveBeenCalled() + resolve() + }) + + dropdown.show() + }) + }) + + it('should not hide a dropdown if the element is disabled', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdownMenu = fixtureEl.querySelector('.dropdown-menu') + const dropdown = new Dropdown(btnDropdown) + + btnDropdown.addEventListener('hidden.bs.dropdown', () => { + reject(new Error('should not throw hidden.bs.dropdown event')) + }) + + dropdown.hide() + + setTimeout(() => { + expect(dropdownMenu).toHaveClass('show') + resolve() + }, 10) + }) + }) + + it('should not hide a dropdown if the element contains .disabled', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdownMenu = fixtureEl.querySelector('.dropdown-menu') + const dropdown = new Dropdown(btnDropdown) + + btnDropdown.addEventListener('hidden.bs.dropdown', () => { + reject(new Error('should not throw hidden.bs.dropdown event')) + }) + + dropdown.hide() + + setTimeout(() => { + expect(dropdownMenu).toHaveClass('show') + resolve() + }, 10) + }) + }) + + it('should not hide a dropdown if the menu is not shown', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdown = new Dropdown(btnDropdown) + + btnDropdown.addEventListener('hidden.bs.dropdown', () => { + reject(new Error('should not throw hidden.bs.dropdown event')) + }) + + dropdown.hide() + + setTimeout(() => { + expect().nothing() + resolve() + }, 10) + }) + }) + + it('should not hide a dropdown if hide event is prevented', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdownMenu = fixtureEl.querySelector('.dropdown-menu') + const dropdown = new Dropdown(btnDropdown) + + btnDropdown.addEventListener('hide.bs.dropdown', event => { + event.preventDefault() + }) + + btnDropdown.addEventListener('hidden.bs.dropdown', () => { + reject(new Error('should not throw hidden.bs.dropdown event')) + }) + + dropdown.hide() + + setTimeout(() => { + expect(dropdownMenu).toHaveClass('show') + resolve() + }) + }) + }) + + it('should remove event listener on touch-enabled device that was added in show method', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const defaultValueOnTouchStart = document.documentElement.ontouchstart + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdown = new Dropdown(btnDropdown) + + document.documentElement.ontouchstart = noop + const spy = spyOn(EventHandler, 'off') + + btnDropdown.addEventListener('shown.bs.dropdown', () => { + dropdown.hide() + }) + + btnDropdown.addEventListener('hidden.bs.dropdown', () => { + expect(btnDropdown).not.toHaveClass('show') + expect(btnDropdown.getAttribute('aria-expanded')).toEqual('false') + expect(spy).toHaveBeenCalled() + + document.documentElement.ontouchstart = defaultValueOnTouchStart + resolve() + }) + + dropdown.show() + }) + }) + }) + + describe('dispose', () => { + it('should dispose dropdown', () => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + + const dropdown = new Dropdown(btnDropdown) + + expect(dropdown._popper).toBeNull() + expect(dropdown._menu).not.toBeNull() + expect(dropdown._element).not.toBeNull() + const spy = spyOn(EventHandler, 'off') + + dropdown.dispose() + + expect(dropdown._menu).toBeNull() + expect(dropdown._element).toBeNull() + expect(spy).toHaveBeenCalledWith(btnDropdown, Dropdown.EVENT_KEY) + }) + + it('should dispose dropdown with Popper', () => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdown = new Dropdown(btnDropdown) + + dropdown.toggle() + + expect(dropdown._popper).not.toBeNull() + expect(dropdown._menu).not.toBeNull() + expect(dropdown._element).not.toBeNull() + + dropdown.dispose() + + expect(dropdown._popper).toBeNull() + expect(dropdown._menu).toBeNull() + expect(dropdown._element).toBeNull() + }) + }) + + describe('update', () => { + it('should call Popper and detect navbar on update', () => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdown = new Dropdown(btnDropdown) + + dropdown.toggle() + + expect(dropdown._popper).not.toBeNull() + + const spyUpdate = spyOn(dropdown._popper, 'update') + const spyDetect = spyOn(dropdown, '_detectNavbar') + + dropdown.update() + + expect(spyUpdate).toHaveBeenCalled() + expect(spyDetect).toHaveBeenCalled() + }) + + it('should just detect navbar on update', () => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdown = new Dropdown(btnDropdown) + + const spy = spyOn(dropdown, '_detectNavbar') + + dropdown.update() + + expect(dropdown._popper).toBeNull() + expect(spy).toHaveBeenCalled() + }) + }) + + describe('data-api', () => { + it('should show and hide a dropdown', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + let showEventTriggered = false + let hideEventTriggered = false + + btnDropdown.addEventListener('show.bs.dropdown', () => { + showEventTriggered = true + }) + + btnDropdown.addEventListener('shown.bs.dropdown', event => setTimeout(() => { + expect(btnDropdown).toHaveClass('show') + expect(btnDropdown.getAttribute('aria-expanded')).toEqual('true') + expect(showEventTriggered).toBeTrue() + expect(event.relatedTarget).toEqual(btnDropdown) + document.body.click() + })) + + btnDropdown.addEventListener('hide.bs.dropdown', () => { + hideEventTriggered = true + }) + + btnDropdown.addEventListener('hidden.bs.dropdown', event => { + expect(btnDropdown).not.toHaveClass('show') + expect(btnDropdown.getAttribute('aria-expanded')).toEqual('false') + expect(hideEventTriggered).toBeTrue() + expect(event.relatedTarget).toEqual(btnDropdown) + resolve() + }) + + btnDropdown.click() + }) + }) + + it('should not use "static" Popper in navbar', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdownMenu = fixtureEl.querySelector('.dropdown-menu') + const dropdown = new Dropdown(btnDropdown) + + btnDropdown.addEventListener('shown.bs.dropdown', () => { + expect(dropdown._popper).not.toBeNull() + expect(dropdownMenu.getAttribute('data-bs-popper')).toEqual('static') + resolve() + }) + + dropdown.show() + }) + }) + + it('should not collapse the dropdown when clicking a select option nested in the dropdown', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdownMenu = fixtureEl.querySelector('.dropdown-menu') + const dropdown = new Dropdown(btnDropdown) + + const hideSpy = spyOn(dropdown, '_completeHide') + + btnDropdown.addEventListener('shown.bs.dropdown', () => { + const clickEvent = new MouseEvent('click', { + bubbles: true + }) + + dropdownMenu.querySelector('option').dispatchEvent(clickEvent) + }) + + dropdownMenu.addEventListener('click', event => { + expect(event.target.tagName).toMatch(/select|option/i) + + Dropdown.clearMenus(event) + + setTimeout(() => { + expect(hideSpy).not.toHaveBeenCalled() + resolve() + }, 10) + }) + + dropdown.show() + }) + }) + + it('should manage bs attribute `data-bs-popper`="static" when dropdown is in navbar', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdownMenu = fixtureEl.querySelector('.dropdown-menu') + const dropdown = new Dropdown(btnDropdown) + + btnDropdown.addEventListener('shown.bs.dropdown', () => { + expect(dropdownMenu.getAttribute('data-bs-popper')).toEqual('static') + dropdown.hide() + }) + + btnDropdown.addEventListener('hidden.bs.dropdown', () => { + expect(dropdownMenu.getAttribute('data-bs-popper')).toBeNull() + resolve() + }) + + dropdown.show() + }) + }) + + it('should not use Popper if display set to static', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdownMenu = fixtureEl.querySelector('.dropdown-menu') + + btnDropdown.addEventListener('shown.bs.dropdown', () => { + // Popper adds this attribute when we use it + expect(dropdownMenu.getAttribute('data-popper-placement')).toBeNull() + resolve() + }) + + btnDropdown.click() + }) + }) + + it('should manage bs attribute `data-bs-popper`="static" when display set to static', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdownMenu = fixtureEl.querySelector('.dropdown-menu') + const dropdown = new Dropdown(btnDropdown) + + btnDropdown.addEventListener('shown.bs.dropdown', () => { + expect(dropdownMenu.getAttribute('data-bs-popper')).toEqual('static') + dropdown.hide() + }) + + btnDropdown.addEventListener('hidden.bs.dropdown', () => { + expect(dropdownMenu.getAttribute('data-bs-popper')).toBeNull() + resolve() + }) + + dropdown.show() + }) + }) + + it('should remove "show" class if tabbing outside of menu', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + + btnDropdown.addEventListener('shown.bs.dropdown', () => { + expect(btnDropdown).toHaveClass('show') + + const keyup = createEvent('keyup') + + keyup.key = 'Tab' + document.dispatchEvent(keyup) + }) + + btnDropdown.addEventListener('hidden.bs.dropdown', () => { + expect(btnDropdown).not.toHaveClass('show') + resolve() + }) + + btnDropdown.click() + }) + }) + + it('should remove "show" class if body is clicked, with multiple dropdowns', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '
', + ' ', + ' ', + ' ', + '
' + ].join('') + + const triggerDropdownList = fixtureEl.querySelectorAll('[data-bs-toggle="dropdown"]') + + expect(triggerDropdownList).toHaveSize(2) + + const [triggerDropdownFirst, triggerDropdownLast] = triggerDropdownList + + triggerDropdownFirst.addEventListener('shown.bs.dropdown', () => { + expect(triggerDropdownFirst).toHaveClass('show') + expect(fixtureEl.querySelectorAll('.dropdown-menu.show')).toHaveSize(1) + document.body.click() + }) + + triggerDropdownFirst.addEventListener('hidden.bs.dropdown', () => { + expect(fixtureEl.querySelectorAll('.dropdown-menu.show')).toHaveSize(0) + triggerDropdownLast.click() + }) + + triggerDropdownLast.addEventListener('shown.bs.dropdown', () => { + expect(triggerDropdownLast).toHaveClass('show') + expect(fixtureEl.querySelectorAll('.dropdown-menu.show')).toHaveSize(1) + document.body.click() + }) + + triggerDropdownLast.addEventListener('hidden.bs.dropdown', () => { + expect(fixtureEl.querySelectorAll('.dropdown-menu.show')).toHaveSize(0) + resolve() + }) + + triggerDropdownFirst.click() + }) + }) + + it('should remove "show" class if body if tabbing outside of menu, with multiple dropdowns', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '
', + ' ', + ' ', + ' ', + '
' + ].join('') + + const triggerDropdownList = fixtureEl.querySelectorAll('[data-bs-toggle="dropdown"]') + + expect(triggerDropdownList).toHaveSize(2) + + const [triggerDropdownFirst, triggerDropdownLast] = triggerDropdownList + + triggerDropdownFirst.addEventListener('shown.bs.dropdown', () => { + expect(triggerDropdownFirst).toHaveClass('show') + expect(fixtureEl.querySelectorAll('.dropdown-menu.show')).toHaveSize(1) + + const keyup = createEvent('keyup') + keyup.key = 'Tab' + + document.dispatchEvent(keyup) + }) + + triggerDropdownFirst.addEventListener('hidden.bs.dropdown', () => { + expect(fixtureEl.querySelectorAll('.dropdown-menu.show')).toHaveSize(0) + triggerDropdownLast.click() + }) + + triggerDropdownLast.addEventListener('shown.bs.dropdown', () => { + expect(triggerDropdownLast).toHaveClass('show') + expect(fixtureEl.querySelectorAll('.dropdown-menu.show')).toHaveSize(1) + + const keyup = createEvent('keyup') + keyup.key = 'Tab' + + document.dispatchEvent(keyup) + }) + + triggerDropdownLast.addEventListener('hidden.bs.dropdown', () => { + expect(fixtureEl.querySelectorAll('.dropdown-menu.show')).toHaveSize(0) + resolve() + }) + + triggerDropdownFirst.click() + }) + }) + + it('should be able to identify clicked dropdown, even with multiple dropdowns in the same tag', () => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const dropdownToggle1 = fixtureEl.querySelector('#dropdown1') + const dropdownToggle2 = fixtureEl.querySelector('#dropdown2') + const dropdownMenu1 = fixtureEl.querySelector('#menu1') + const dropdownMenu2 = fixtureEl.querySelector('#menu2') + const spy = spyOn(Dropdown, 'getOrCreateInstance').and.callThrough() + + dropdownToggle1.click() + expect(spy).toHaveBeenCalledWith(dropdownToggle1) + + dropdownToggle2.click() + expect(spy).toHaveBeenCalledWith(dropdownToggle2) + + dropdownMenu1.click() + expect(spy).toHaveBeenCalledWith(dropdownToggle1) + + dropdownMenu2.click() + expect(spy).toHaveBeenCalledWith(dropdownToggle2) + }) + + it('should be able to show the proper menu, even with multiple dropdowns in the same tag', () => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const dropdownToggle1 = fixtureEl.querySelector('#dropdown1') + const dropdownToggle2 = fixtureEl.querySelector('#dropdown2') + const dropdownMenu1 = fixtureEl.querySelector('#menu1') + const dropdownMenu2 = fixtureEl.querySelector('#menu2') + + dropdownToggle1.click() + expect(dropdownMenu1).toHaveClass('show') + expect(dropdownMenu2).not.toHaveClass('show') + + dropdownToggle2.click() + expect(dropdownMenu1).not.toHaveClass('show') + expect(dropdownMenu2).toHaveClass('show') + }) + + it('should fire hide and hidden event without a clickEvent if event type is not click', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const triggerDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + + triggerDropdown.addEventListener('hide.bs.dropdown', event => { + expect(event.clickEvent).toBeUndefined() + }) + + triggerDropdown.addEventListener('hidden.bs.dropdown', event => { + expect(event.clickEvent).toBeUndefined() + resolve() + }) + + triggerDropdown.addEventListener('shown.bs.dropdown', () => { + const keydown = createEvent('keydown') + + keydown.key = 'Escape' + triggerDropdown.dispatchEvent(keydown) + }) + + triggerDropdown.click() + }) + }) + + it('should bubble up the events to the parent elements', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const triggerDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdownParent = fixtureEl.querySelector('.dropdown') + const dropdown = new Dropdown(triggerDropdown) + + const showFunction = jasmine.createSpy('showFunction') + dropdownParent.addEventListener('show.bs.dropdown', showFunction) + + const shownFunction = jasmine.createSpy('shownFunction') + dropdownParent.addEventListener('shown.bs.dropdown', () => { + shownFunction() + dropdown.hide() + }) + + const hideFunction = jasmine.createSpy('hideFunction') + dropdownParent.addEventListener('hide.bs.dropdown', hideFunction) + + dropdownParent.addEventListener('hidden.bs.dropdown', () => { + expect(showFunction).toHaveBeenCalled() + expect(shownFunction).toHaveBeenCalled() + expect(hideFunction).toHaveBeenCalled() + resolve() + }) + + dropdown.show() + }) + }) + + it('should ignore keyboard events within s and ', + ' ', + '' + ].join('') + + const triggerDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const input = fixtureEl.querySelector('input') + const textarea = fixtureEl.querySelector('textarea') + + triggerDropdown.addEventListener('shown.bs.dropdown', () => { + input.focus() + const keydown = createEvent('keydown') + + keydown.key = 'ArrowUp' + input.dispatchEvent(keydown) + + expect(document.activeElement).toEqual(input, 'input still focused') + + textarea.focus() + textarea.dispatchEvent(keydown) + + expect(document.activeElement).toEqual(textarea, 'textarea still focused') + resolve() + }) + + triggerDropdown.click() + }) + }) + + it('should skip disabled element when using keyboard navigation', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const triggerDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + + triggerDropdown.addEventListener('shown.bs.dropdown', () => { + const keydown = createEvent('keydown') + keydown.key = 'ArrowDown' + + triggerDropdown.dispatchEvent(keydown) + triggerDropdown.dispatchEvent(keydown) + + expect(document.activeElement).not.toHaveClass('disabled') + expect(document.activeElement.hasAttribute('disabled')).toBeFalse() + resolve() + }) + + triggerDropdown.click() + }) + }) + + it('should skip hidden element when using keyboard navigation', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '' + ].join('') + + const triggerDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + + triggerDropdown.addEventListener('shown.bs.dropdown', () => { + const keydown = createEvent('keydown') + keydown.key = 'ArrowDown' + + triggerDropdown.dispatchEvent(keydown) + + expect(document.activeElement).not.toHaveClass('d-none') + expect(document.activeElement.style.display).not.toEqual('none') + expect(document.activeElement.style.visibility).not.toEqual('hidden') + + resolve() + }) + + triggerDropdown.click() + }) + }) + + it('should focus next/previous element when using keyboard navigation', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const triggerDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const item1 = fixtureEl.querySelector('#item1') + const item2 = fixtureEl.querySelector('#item2') + + triggerDropdown.addEventListener('shown.bs.dropdown', () => { + const keydownArrowDown = createEvent('keydown') + keydownArrowDown.key = 'ArrowDown' + + triggerDropdown.dispatchEvent(keydownArrowDown) + expect(document.activeElement).toEqual(item1, 'item1 is focused') + + document.activeElement.dispatchEvent(keydownArrowDown) + expect(document.activeElement).toEqual(item2, 'item2 is focused') + + const keydownArrowUp = createEvent('keydown') + keydownArrowUp.key = 'ArrowUp' + + document.activeElement.dispatchEvent(keydownArrowUp) + expect(document.activeElement).toEqual(item1, 'item1 is focused') + + resolve() + }) + + triggerDropdown.click() + }) + }) + + it('should open the dropdown and focus on the last item when using ArrowUp for the first time', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const triggerDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const lastItem = fixtureEl.querySelector('#item2') + + triggerDropdown.addEventListener('shown.bs.dropdown', () => { + setTimeout(() => { + expect(document.activeElement).toEqual(lastItem, 'item2 is focused') + resolve() + }) + }) + + const keydown = createEvent('keydown') + keydown.key = 'ArrowUp' + triggerDropdown.dispatchEvent(keydown) + }) + }) + + it('should open the dropdown and focus on the first item when using ArrowDown for the first time', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const triggerDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const firstItem = fixtureEl.querySelector('#item1') + + triggerDropdown.addEventListener('shown.bs.dropdown', () => { + setTimeout(() => { + expect(document.activeElement).toEqual(firstItem, 'item1 is focused') + resolve() + }) + }) + + const keydown = createEvent('keydown') + keydown.key = 'ArrowDown' + triggerDropdown.dispatchEvent(keydown) + }) + }) + + it('should not close the dropdown if the user clicks on a text field within dropdown-menu', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const triggerDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const input = fixtureEl.querySelector('input') + + input.addEventListener('click', () => { + expect(triggerDropdown).toHaveClass('show') + resolve() + }) + + triggerDropdown.addEventListener('shown.bs.dropdown', () => { + expect(triggerDropdown).toHaveClass('show') + input.dispatchEvent(createEvent('click')) + }) + + triggerDropdown.click() + }) + }) + + it('should not close the dropdown if the user clicks on a textarea within dropdown-menu', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const triggerDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const textarea = fixtureEl.querySelector('textarea') + + textarea.addEventListener('click', () => { + expect(triggerDropdown).toHaveClass('show') + resolve() + }) + + triggerDropdown.addEventListener('shown.bs.dropdown', () => { + expect(triggerDropdown).toHaveClass('show') + textarea.dispatchEvent(createEvent('click')) + }) + + triggerDropdown.click() + }) + }) + + it('should close the dropdown if the user clicks on a text field that is not contained within dropdown-menu', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '' + ].join('') + + const triggerDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const input = fixtureEl.querySelector('input') + + triggerDropdown.addEventListener('hidden.bs.dropdown', () => { + expect().nothing() + resolve() + }) + + triggerDropdown.addEventListener('shown.bs.dropdown', () => { + input.dispatchEvent(createEvent('click', { + bubbles: true + })) + }) + + triggerDropdown.click() + }) + }) + + it('should ignore keyboard events for s and ', + ' ', + '' + ].join('') + + const triggerDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const input = fixtureEl.querySelector('input') + const textarea = fixtureEl.querySelector('textarea') + + const test = (eventKey, elementToDispatch) => { + const event = createEvent('keydown') + event.key = eventKey + elementToDispatch.focus() + elementToDispatch.dispatchEvent(event) + expect(document.activeElement).toEqual(elementToDispatch, `${elementToDispatch.tagName} still focused`) + } + + const keydownEscape = createEvent('keydown') + keydownEscape.key = 'Escape' + + triggerDropdown.addEventListener('shown.bs.dropdown', () => { + // Key Space + test('Space', input) + + test('Space', textarea) + + // Key ArrowUp + test('ArrowUp', input) + + test('ArrowUp', textarea) + + // Key ArrowDown + test('ArrowDown', input) + + test('ArrowDown', textarea) + + // Key Escape + input.focus() + input.dispatchEvent(keydownEscape) + + expect(triggerDropdown).not.toHaveClass('show') + resolve() + }) + + triggerDropdown.click() + }) + }) + + it('should not open dropdown if escape key was pressed on the toggle', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '
', + ' ', + '
' + ].join('') + + const triggerDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdown = new Dropdown(triggerDropdown) + const button = fixtureEl.querySelector('button[data-bs-toggle="dropdown"]') + + const spy = spyOn(dropdown, 'toggle') + + // Key escape + button.focus() + // Key escape + const keydownEscape = createEvent('keydown') + keydownEscape.key = 'Escape' + button.dispatchEvent(keydownEscape) + + setTimeout(() => { + expect(spy).not.toHaveBeenCalled() + expect(triggerDropdown).not.toHaveClass('show') + resolve() + }, 20) + }) + }) + + it('should propagate escape key events if dropdown is closed', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '
', + ' ', + '
' + ].join('') + + const parent = fixtureEl.querySelector('.parent') + const toggle = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + + const parentKeyHandler = jasmine.createSpy('parentKeyHandler') + + parent.addEventListener('keydown', parentKeyHandler) + parent.addEventListener('keyup', () => { + expect(parentKeyHandler).toHaveBeenCalled() + resolve() + }) + + const keydownEscape = createEvent('keydown', { bubbles: true }) + keydownEscape.key = 'Escape' + const keyupEscape = createEvent('keyup', { bubbles: true }) + keyupEscape.key = 'Escape' + + toggle.focus() + toggle.dispatchEvent(keydownEscape) + toggle.dispatchEvent(keyupEscape) + }) + }) + + it('should not propagate escape key events if dropdown is open', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '
', + ' ', + '
' + ].join('') + + const parent = fixtureEl.querySelector('.parent') + const toggle = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + + const parentKeyHandler = jasmine.createSpy('parentKeyHandler') + + parent.addEventListener('keydown', parentKeyHandler) + parent.addEventListener('keyup', () => { + expect(parentKeyHandler).not.toHaveBeenCalled() + resolve() + }) + + const keydownEscape = createEvent('keydown', { bubbles: true }) + keydownEscape.key = 'Escape' + const keyupEscape = createEvent('keyup', { bubbles: true }) + keyupEscape.key = 'Escape' + + toggle.click() + toggle.dispatchEvent(keydownEscape) + toggle.dispatchEvent(keyupEscape) + }) + }) + + it('should close dropdown using `escape` button, and return focus to its trigger', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const toggle = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + + toggle.addEventListener('shown.bs.dropdown', () => { + const keydownEvent = createEvent('keydown', { bubbles: true }) + keydownEvent.key = 'ArrowDown' + toggle.dispatchEvent(keydownEvent) + keydownEvent.key = 'Escape' + toggle.dispatchEvent(keydownEvent) + }) + + toggle.addEventListener('hidden.bs.dropdown', () => setTimeout(() => { + expect(document.activeElement).toEqual(toggle) + resolve() + })) + + toggle.click() + }) + }) + + it('should close dropdown (only) by clicking inside the dropdown menu when it has data-attribute `data-bs-auto-close="inside"`', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const dropdownToggle = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdownMenu = fixtureEl.querySelector('.dropdown-menu') + + const expectDropdownToBeOpened = () => setTimeout(() => { + expect(dropdownToggle).toHaveClass('show') + dropdownMenu.click() + }, 150) + + dropdownToggle.addEventListener('shown.bs.dropdown', () => { + document.documentElement.click() + expectDropdownToBeOpened() + }) + + dropdownToggle.addEventListener('hidden.bs.dropdown', () => setTimeout(() => { + expect(dropdownToggle).not.toHaveClass('show') + resolve() + })) + + dropdownToggle.click() + }) + }) + + it('should close dropdown (only) by clicking outside the dropdown menu when it has data-attribute `data-bs-auto-close="outside"`', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const dropdownToggle = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdownMenu = fixtureEl.querySelector('.dropdown-menu') + + const expectDropdownToBeOpened = () => setTimeout(() => { + expect(dropdownToggle).toHaveClass('show') + document.documentElement.click() + }, 150) + + dropdownToggle.addEventListener('shown.bs.dropdown', () => { + dropdownMenu.click() + expectDropdownToBeOpened() + }) + + dropdownToggle.addEventListener('hidden.bs.dropdown', () => { + expect(dropdownToggle).not.toHaveClass('show') + resolve() + }) + + dropdownToggle.click() + }) + }) + + it('should not close dropdown by clicking inside or outside the dropdown menu when it has data-attribute `data-bs-auto-close="false"`', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const dropdownToggle = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdownMenu = fixtureEl.querySelector('.dropdown-menu') + + const expectDropdownToBeOpened = (shouldTriggerClick = true) => setTimeout(() => { + expect(dropdownToggle).toHaveClass('show') + if (shouldTriggerClick) { + document.documentElement.click() + } else { + resolve() + } + + expectDropdownToBeOpened(false) + }, 150) + + dropdownToggle.addEventListener('shown.bs.dropdown', () => { + dropdownMenu.click() + expectDropdownToBeOpened() + }) + + dropdownToggle.click() + }) + }) + + it('should be able to identify clicked dropdown, no matter the markup order', () => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const dropdownToggle = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdownMenu = fixtureEl.querySelector('.dropdown-menu') + const spy = spyOn(Dropdown, 'getOrCreateInstance').and.callThrough() + + dropdownToggle.click() + expect(spy).toHaveBeenCalledWith(dropdownToggle) + dropdownMenu.click() + expect(spy).toHaveBeenCalledWith(dropdownToggle) + }) + }) + + describe('jQueryInterface', () => { + it('should create a dropdown', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + jQueryMock.fn.dropdown = Dropdown.jQueryInterface + jQueryMock.elements = [div] + + jQueryMock.fn.dropdown.call(jQueryMock) + + expect(Dropdown.getInstance(div)).not.toBeNull() + }) + + it('should not re create a dropdown', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const dropdown = new Dropdown(div) + + jQueryMock.fn.dropdown = Dropdown.jQueryInterface + jQueryMock.elements = [div] + + jQueryMock.fn.dropdown.call(jQueryMock) + + expect(Dropdown.getInstance(div)).toEqual(dropdown) + }) + + it('should throw error on undefined method', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const action = 'undefinedMethod' + + jQueryMock.fn.dropdown = Dropdown.jQueryInterface + jQueryMock.elements = [div] + + expect(() => { + jQueryMock.fn.dropdown.call(jQueryMock, action) + }).toThrowError(TypeError, `No method named "${action}"`) + }) + }) + + describe('getInstance', () => { + it('should return dropdown instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const dropdown = new Dropdown(div) + + expect(Dropdown.getInstance(div)).toEqual(dropdown) + expect(Dropdown.getInstance(div)).toBeInstanceOf(Dropdown) + }) + + it('should return null when there is no dropdown instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(Dropdown.getInstance(div)).toBeNull() + }) + }) + + describe('getOrCreateInstance', () => { + it('should return dropdown instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const dropdown = new Dropdown(div) + + expect(Dropdown.getOrCreateInstance(div)).toEqual(dropdown) + expect(Dropdown.getInstance(div)).toEqual(Dropdown.getOrCreateInstance(div, {})) + expect(Dropdown.getOrCreateInstance(div)).toBeInstanceOf(Dropdown) + }) + + it('should return new instance when there is no dropdown instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(Dropdown.getInstance(div)).toBeNull() + expect(Dropdown.getOrCreateInstance(div)).toBeInstanceOf(Dropdown) + }) + + it('should return new instance when there is no dropdown instance with given configuration', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(Dropdown.getInstance(div)).toBeNull() + const dropdown = Dropdown.getOrCreateInstance(div, { + display: 'dynamic' + }) + expect(dropdown).toBeInstanceOf(Dropdown) + + expect(dropdown._config.display).toEqual('dynamic') + }) + + it('should return the instance when exists without given configuration', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const dropdown = new Dropdown(div, { + display: 'dynamic' + }) + expect(Dropdown.getInstance(div)).toEqual(dropdown) + + const dropdown2 = Dropdown.getOrCreateInstance(div, { + display: 'static' + }) + expect(dropdown).toBeInstanceOf(Dropdown) + expect(dropdown2).toEqual(dropdown) + + expect(dropdown2._config.display).toEqual('dynamic') + }) + }) + + it('should open dropdown when pressing keydown or keyup', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const triggerDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const dropdown = fixtureEl.querySelector('.dropdown') + + const keydown = createEvent('keydown') + keydown.key = 'ArrowDown' + + const keyup = createEvent('keyup') + keyup.key = 'ArrowUp' + + const handleArrowDown = () => { + expect(triggerDropdown).toHaveClass('show') + expect(triggerDropdown.getAttribute('aria-expanded')).toEqual('true') + setTimeout(() => { + dropdown.hide() + keydown.key = 'ArrowUp' + triggerDropdown.dispatchEvent(keyup) + }, 20) + } + + const handleArrowUp = () => { + expect(triggerDropdown).toHaveClass('show') + expect(triggerDropdown.getAttribute('aria-expanded')).toEqual('true') + resolve() + } + + dropdown.addEventListener('shown.bs.dropdown', event => { + if (event.target.key === 'ArrowDown') { + handleArrowDown() + } else { + handleArrowUp() + } + }) + + triggerDropdown.dispatchEvent(keydown) + }) + }) + + it('should allow `data-bs-toggle="dropdown"` click events to bubble up', () => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const clickListener = jasmine.createSpy('clickListener') + const delegatedClickListener = jasmine.createSpy('delegatedClickListener') + + btnDropdown.addEventListener('click', clickListener) + document.addEventListener('click', delegatedClickListener) + + btnDropdown.click() + + expect(clickListener).toHaveBeenCalled() + expect(delegatedClickListener).toHaveBeenCalled() + }) + + it('should open the dropdown when clicking the child element inside `data-bs-toggle="dropdown"`', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '
', + ' ', + '
' + ].join('') + + const btnDropdown = fixtureEl.querySelector('[data-bs-toggle="dropdown"]') + const childElement = fixtureEl.querySelector('#childElement') + + btnDropdown.addEventListener('shown.bs.dropdown', () => setTimeout(() => { + expect(btnDropdown).toHaveClass('show') + expect(btnDropdown.getAttribute('aria-expanded')).toEqual('true') + resolve() + })) + + childElement.click() + }) + }) +}) diff --git a/js/tests/unit/jquery.spec.js b/js/tests/unit/jquery.spec.js new file mode 100644 index 0000000..7da39d6 --- /dev/null +++ b/js/tests/unit/jquery.spec.js @@ -0,0 +1,60 @@ +/* eslint-env jquery */ + +import Alert from '../../src/alert' +import Button from '../../src/button' +import Carousel from '../../src/carousel' +import Collapse from '../../src/collapse' +import Dropdown from '../../src/dropdown' +import Modal from '../../src/modal' +import Offcanvas from '../../src/offcanvas' +import Popover from '../../src/popover' +import ScrollSpy from '../../src/scrollspy' +import Tab from '../../src/tab' +import Toast from '../../src/toast' +import Tooltip from '../../src/tooltip' +import { clearFixture, getFixture } from '../helpers/fixture' + +describe('jQuery', () => { + let fixtureEl + + beforeAll(() => { + fixtureEl = getFixture() + }) + + afterEach(() => { + clearFixture() + }) + + it('should add all plugins in jQuery', () => { + expect(Alert.jQueryInterface).toEqual(jQuery.fn.alert) + expect(Button.jQueryInterface).toEqual(jQuery.fn.button) + expect(Carousel.jQueryInterface).toEqual(jQuery.fn.carousel) + expect(Collapse.jQueryInterface).toEqual(jQuery.fn.collapse) + expect(Dropdown.jQueryInterface).toEqual(jQuery.fn.dropdown) + expect(Modal.jQueryInterface).toEqual(jQuery.fn.modal) + expect(Offcanvas.jQueryInterface).toEqual(jQuery.fn.offcanvas) + expect(Popover.jQueryInterface).toEqual(jQuery.fn.popover) + expect(ScrollSpy.jQueryInterface).toEqual(jQuery.fn.scrollspy) + expect(Tab.jQueryInterface).toEqual(jQuery.fn.tab) + expect(Toast.jQueryInterface).toEqual(jQuery.fn.toast) + expect(Tooltip.jQueryInterface).toEqual(jQuery.fn.tooltip) + }) + + it('should use jQuery event system', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '
', + ' ', + '
' + ].join('') + + $(fixtureEl).find('.alert') + .one('closed.bs.alert', () => { + expect($(fixtureEl).find('.alert')).toHaveSize(0) + resolve() + }) + + $(fixtureEl).find('button').trigger('click') + }) + }) +}) diff --git a/js/tests/unit/modal.spec.js b/js/tests/unit/modal.spec.js new file mode 100644 index 0000000..fdee29e --- /dev/null +++ b/js/tests/unit/modal.spec.js @@ -0,0 +1,1298 @@ +import Modal from '../../src/modal' +import EventHandler from '../../src/dom/event-handler' +import ScrollBarHelper from '../../src/util/scrollbar' +import { clearBodyAndDocument, clearFixture, createEvent, getFixture, jQueryMock } from '../helpers/fixture' + +describe('Modal', () => { + let fixtureEl + + beforeAll(() => { + fixtureEl = getFixture() + }) + + afterEach(() => { + clearFixture() + clearBodyAndDocument() + document.body.classList.remove('modal-open') + + for (const backdrop of document.querySelectorAll('.modal-backdrop')) { + backdrop.remove() + } + }) + + beforeEach(() => { + clearBodyAndDocument() + }) + + describe('VERSION', () => { + it('should return plugin version', () => { + expect(Modal.VERSION).toEqual(jasmine.any(String)) + }) + }) + + describe('Default', () => { + it('should return plugin default config', () => { + expect(Modal.Default).toEqual(jasmine.any(Object)) + }) + }) + + describe('DATA_KEY', () => { + it('should return plugin data key', () => { + expect(Modal.DATA_KEY).toEqual('bs.modal') + }) + }) + + describe('constructor', () => { + it('should take care of element either passed as a CSS selector or DOM element', () => { + fixtureEl.innerHTML = '' + + const modalEl = fixtureEl.querySelector('.modal') + const modalBySelector = new Modal('.modal') + const modalByElement = new Modal(modalEl) + + expect(modalBySelector._element).toEqual(modalEl) + expect(modalByElement._element).toEqual(modalEl) + }) + }) + + describe('toggle', () => { + it('should call ScrollBarHelper to handle scrollBar on body', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const spyHide = spyOn(ScrollBarHelper.prototype, 'hide').and.callThrough() + const spyReset = spyOn(ScrollBarHelper.prototype, 'reset').and.callThrough() + const modalEl = fixtureEl.querySelector('.modal') + const modal = new Modal(modalEl) + + modalEl.addEventListener('shown.bs.modal', () => { + expect(spyHide).toHaveBeenCalled() + modal.toggle() + }) + + modalEl.addEventListener('hidden.bs.modal', () => { + expect(spyReset).toHaveBeenCalled() + resolve() + }) + + modal.toggle() + }) + }) + }) + + describe('show', () => { + it('should show a modal', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const modalEl = fixtureEl.querySelector('.modal') + const modal = new Modal(modalEl) + + modalEl.addEventListener('show.bs.modal', event => { + expect(event).toBeDefined() + }) + + modalEl.addEventListener('shown.bs.modal', () => { + expect(modalEl.getAttribute('aria-modal')).toEqual('true') + expect(modalEl.getAttribute('role')).toEqual('dialog') + expect(modalEl.getAttribute('aria-hidden')).toBeNull() + expect(modalEl.style.display).toEqual('block') + expect(document.querySelector('.modal-backdrop')).not.toBeNull() + resolve() + }) + + modal.show() + }) + }) + + it('should show a modal without backdrop', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const modalEl = fixtureEl.querySelector('.modal') + const modal = new Modal(modalEl, { + backdrop: false + }) + + modalEl.addEventListener('show.bs.modal', event => { + expect(event).toBeDefined() + }) + + modalEl.addEventListener('shown.bs.modal', () => { + expect(modalEl.getAttribute('aria-modal')).toEqual('true') + expect(modalEl.getAttribute('role')).toEqual('dialog') + expect(modalEl.getAttribute('aria-hidden')).toBeNull() + expect(modalEl.style.display).toEqual('block') + expect(document.querySelector('.modal-backdrop')).toBeNull() + resolve() + }) + + modal.show() + }) + }) + + it('should show a modal and append the element', () => { + return new Promise(resolve => { + const modalEl = document.createElement('div') + const id = 'dynamicModal' + + modalEl.setAttribute('id', id) + modalEl.classList.add('modal') + modalEl.innerHTML = '' + + const modal = new Modal(modalEl) + + modalEl.addEventListener('shown.bs.modal', () => { + const dynamicModal = document.getElementById(id) + expect(dynamicModal).not.toBeNull() + dynamicModal.remove() + resolve() + }) + + modal.show() + }) + }) + + it('should do nothing if a modal is shown', () => { + fixtureEl.innerHTML = '' + + const modalEl = fixtureEl.querySelector('.modal') + const modal = new Modal(modalEl) + + const spy = spyOn(EventHandler, 'trigger') + modal._isShown = true + + modal.show() + + expect(spy).not.toHaveBeenCalled() + }) + + it('should do nothing if a modal is transitioning', () => { + fixtureEl.innerHTML = '' + + const modalEl = fixtureEl.querySelector('.modal') + const modal = new Modal(modalEl) + + const spy = spyOn(EventHandler, 'trigger') + modal._isTransitioning = true + + modal.show() + + expect(spy).not.toHaveBeenCalled() + }) + + it('should not fire shown event when show is prevented', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = '' + + const modalEl = fixtureEl.querySelector('.modal') + const modal = new Modal(modalEl) + + modalEl.addEventListener('show.bs.modal', event => { + event.preventDefault() + + const expectedDone = () => { + expect().nothing() + resolve() + } + + setTimeout(expectedDone, 10) + }) + + modalEl.addEventListener('shown.bs.modal', () => { + reject(new Error('shown event triggered')) + }) + + modal.show() + }) + }) + + it('should be shown after the first call to show() has been prevented while fading is enabled ', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const modalEl = fixtureEl.querySelector('.modal') + const modal = new Modal(modalEl) + + let prevented = false + modalEl.addEventListener('show.bs.modal', event => { + if (!prevented) { + event.preventDefault() + prevented = true + + setTimeout(() => { + modal.show() + }) + } + }) + + modalEl.addEventListener('shown.bs.modal', () => { + expect(prevented).toBeTrue() + expect(modal._isAnimated()).toBeTrue() + resolve() + }) + + modal.show() + }) + }) + it('should set is transitioning if fade class is present', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const modalEl = fixtureEl.querySelector('.modal') + const modal = new Modal(modalEl) + + modalEl.addEventListener('show.bs.modal', () => { + setTimeout(() => { + expect(modal._isTransitioning).toBeTrue() + }) + }) + + modalEl.addEventListener('shown.bs.modal', () => { + expect(modal._isTransitioning).toBeFalse() + resolve() + }) + + modal.show() + }) + }) + + it('should close modal when a click occurred on data-bs-dismiss="modal" inside modal', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const modalEl = fixtureEl.querySelector('.modal') + const btnClose = fixtureEl.querySelector('[data-bs-dismiss="modal"]') + const modal = new Modal(modalEl) + + const spy = spyOn(modal, 'hide').and.callThrough() + + modalEl.addEventListener('shown.bs.modal', () => { + btnClose.click() + }) + + modalEl.addEventListener('hidden.bs.modal', () => { + expect(spy).toHaveBeenCalled() + resolve() + }) + + modal.show() + }) + }) + + it('should close modal when a click occurred on a data-bs-dismiss="modal" with "bs-target" outside of modal element', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '' + ].join('') + + const modalEl = fixtureEl.querySelector('.modal') + const btnClose = fixtureEl.querySelector('[data-bs-dismiss="modal"]') + const modal = new Modal(modalEl) + + const spy = spyOn(modal, 'hide').and.callThrough() + + modalEl.addEventListener('shown.bs.modal', () => { + btnClose.click() + }) + + modalEl.addEventListener('hidden.bs.modal', () => { + expect(spy).toHaveBeenCalled() + resolve() + }) + + modal.show() + }) + }) + + it('should set .modal\'s scroll top to 0', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const modalEl = fixtureEl.querySelector('.modal') + const modal = new Modal(modalEl) + + modalEl.addEventListener('shown.bs.modal', () => { + expect(modalEl.scrollTop).toEqual(0) + resolve() + }) + + modal.show() + }) + }) + + it('should set modal body scroll top to 0 if modal body do not exists', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const modalEl = fixtureEl.querySelector('.modal') + const modalBody = modalEl.querySelector('.modal-body') + const modal = new Modal(modalEl) + + modalEl.addEventListener('shown.bs.modal', () => { + expect(modalBody.scrollTop).toEqual(0) + resolve() + }) + + modal.show() + }) + }) + + it('should not trap focus if focus equal to false', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const modalEl = fixtureEl.querySelector('.modal') + const modal = new Modal(modalEl, { + focus: false + }) + + const spy = spyOn(modal._focustrap, 'activate').and.callThrough() + + modalEl.addEventListener('shown.bs.modal', () => { + expect(spy).not.toHaveBeenCalled() + resolve() + }) + + modal.show() + }) + }) + + it('should add listener when escape touch is pressed', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const modalEl = fixtureEl.querySelector('.modal') + const modal = new Modal(modalEl) + + const spy = spyOn(modal, 'hide').and.callThrough() + + modalEl.addEventListener('shown.bs.modal', () => { + const keydownEscape = createEvent('keydown') + keydownEscape.key = 'Escape' + + modalEl.dispatchEvent(keydownEscape) + }) + + modalEl.addEventListener('hidden.bs.modal', () => { + expect(spy).toHaveBeenCalled() + resolve() + }) + + modal.show() + }) + }) + + it('should do nothing when the pressed key is not escape', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const modalEl = fixtureEl.querySelector('.modal') + const modal = new Modal(modalEl) + + const spy = spyOn(modal, 'hide') + + const expectDone = () => { + expect(spy).not.toHaveBeenCalled() + + resolve() + } + + modalEl.addEventListener('shown.bs.modal', () => { + const keydownTab = createEvent('keydown') + keydownTab.key = 'Tab' + + modalEl.dispatchEvent(keydownTab) + setTimeout(expectDone, 30) + }) + + modal.show() + }) + }) + + it('should adjust dialog on resize', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const modalEl = fixtureEl.querySelector('.modal') + const modal = new Modal(modalEl) + + const spy = spyOn(modal, '_adjustDialog').and.callThrough() + + const expectDone = () => { + expect(spy).toHaveBeenCalled() + + resolve() + } + + modalEl.addEventListener('shown.bs.modal', () => { + const resizeEvent = createEvent('resize') + + window.dispatchEvent(resizeEvent) + setTimeout(expectDone, 10) + }) + + modal.show() + }) + }) + + it('should not close modal when clicking on modal-content', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const modalEl = fixtureEl.querySelector('.modal') + const modal = new Modal(modalEl) + + const shownCallback = () => { + setTimeout(() => { + expect(modal._isShown).toEqual(true) + resolve() + }, 10) + } + + modalEl.addEventListener('shown.bs.modal', () => { + fixtureEl.querySelector('.modal-dialog').click() + fixtureEl.querySelector('.modal-content').click() + shownCallback() + }) + + modalEl.addEventListener('hidden.bs.modal', () => { + reject(new Error('Should not hide a modal')) + }) + + modal.show() + }) + }) + + it('should not close modal when clicking outside of modal-content if backdrop = false', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = '' + + const modalEl = fixtureEl.querySelector('.modal') + const modal = new Modal(modalEl, { + backdrop: false + }) + + const shownCallback = () => { + setTimeout(() => { + expect(modal._isShown).toBeTrue() + resolve() + }, 10) + } + + modalEl.addEventListener('shown.bs.modal', () => { + modalEl.click() + shownCallback() + }) + + modalEl.addEventListener('hidden.bs.modal', () => { + reject(new Error('Should not hide a modal')) + }) + + modal.show() + }) + }) + + it('should not close modal when clicking outside of modal-content if backdrop = static', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = '' + + const modalEl = fixtureEl.querySelector('.modal') + const modal = new Modal(modalEl, { + backdrop: 'static' + }) + + const shownCallback = () => { + setTimeout(() => { + expect(modal._isShown).toBeTrue() + resolve() + }, 10) + } + + modalEl.addEventListener('shown.bs.modal', () => { + modalEl.click() + shownCallback() + }) + + modalEl.addEventListener('hidden.bs.modal', () => { + reject(new Error('Should not hide a modal')) + }) + + modal.show() + }) + }) + it('should close modal when escape key is pressed with keyboard = true and backdrop is static', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const modalEl = fixtureEl.querySelector('.modal') + const modal = new Modal(modalEl, { + backdrop: 'static', + keyboard: true + }) + + const shownCallback = () => { + setTimeout(() => { + expect(modal._isShown).toBeFalse() + resolve() + }, 10) + } + + modalEl.addEventListener('shown.bs.modal', () => { + const keydownEscape = createEvent('keydown') + keydownEscape.key = 'Escape' + + modalEl.dispatchEvent(keydownEscape) + shownCallback() + }) + + modal.show() + }) + }) + + it('should not close modal when escape key is pressed with keyboard = false', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = '' + + const modalEl = fixtureEl.querySelector('.modal') + const modal = new Modal(modalEl, { + keyboard: false + }) + + const shownCallback = () => { + setTimeout(() => { + expect(modal._isShown).toBeTrue() + resolve() + }, 10) + } + + modalEl.addEventListener('shown.bs.modal', () => { + const keydownEscape = createEvent('keydown') + keydownEscape.key = 'Escape' + + modalEl.dispatchEvent(keydownEscape) + shownCallback() + }) + + modalEl.addEventListener('hidden.bs.modal', () => { + reject(new Error('Should not hide a modal')) + }) + + modal.show() + }) + }) + + it('should not overflow when clicking outside of modal-content if backdrop = static', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const modalEl = fixtureEl.querySelector('.modal') + const modal = new Modal(modalEl, { + backdrop: 'static' + }) + + modalEl.addEventListener('shown.bs.modal', () => { + modalEl.click() + setTimeout(() => { + expect(modalEl.clientHeight).toEqual(modalEl.scrollHeight) + resolve() + }, 20) + }) + + modal.show() + }) + }) + + it('should not queue multiple callbacks when clicking outside of modal-content and backdrop = static', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const modalEl = fixtureEl.querySelector('.modal') + const modal = new Modal(modalEl, { + backdrop: 'static' + }) + + modalEl.addEventListener('shown.bs.modal', () => { + const spy = spyOn(modal, '_queueCallback').and.callThrough() + const mouseDown = createEvent('mousedown') + + modalEl.dispatchEvent(mouseDown) + modalEl.click() + modalEl.dispatchEvent(mouseDown) + modalEl.click() + + setTimeout(() => { + expect(spy).toHaveBeenCalledTimes(1) + resolve() + }, 20) + }) + + modal.show() + }) + }) + + it('should trap focus', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const modalEl = fixtureEl.querySelector('.modal') + const modal = new Modal(modalEl) + + const spy = spyOn(modal._focustrap, 'activate').and.callThrough() + + modalEl.addEventListener('shown.bs.modal', () => { + expect(spy).toHaveBeenCalled() + resolve() + }) + + modal.show() + }) + }) + }) + + describe('hide', () => { + it('should hide a modal', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const modalEl = fixtureEl.querySelector('.modal') + const modal = new Modal(modalEl) + const backdropSpy = spyOn(modal._backdrop, 'hide').and.callThrough() + + modalEl.addEventListener('shown.bs.modal', () => { + modal.hide() + }) + + modalEl.addEventListener('hide.bs.modal', event => { + expect(event).toBeDefined() + }) + + modalEl.addEventListener('hidden.bs.modal', () => { + expect(modalEl.getAttribute('aria-modal')).toBeNull() + expect(modalEl.getAttribute('role')).toBeNull() + expect(modalEl.getAttribute('aria-hidden')).toEqual('true') + expect(modalEl.style.display).toEqual('none') + expect(backdropSpy).toHaveBeenCalled() + resolve() + }) + + modal.show() + }) + }) + + it('should close modal when clicking outside of modal-content', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const modalEl = fixtureEl.querySelector('.modal') + const dialogEl = modalEl.querySelector('.modal-dialog') + const modal = new Modal(modalEl) + + const spy = spyOn(modal, 'hide') + + modalEl.addEventListener('shown.bs.modal', () => { + const mouseDown = createEvent('mousedown') + + dialogEl.dispatchEvent(mouseDown) + modalEl.click() + expect(spy).not.toHaveBeenCalled() + + modalEl.dispatchEvent(mouseDown) + modalEl.click() + expect(spy).toHaveBeenCalled() + resolve() + }) + + modal.show() + }) + }) + + it('should not close modal when clicking on an element removed from modal content', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const modalEl = fixtureEl.querySelector('.modal') + const buttonEl = modalEl.querySelector('.btn') + const modal = new Modal(modalEl) + + const spy = spyOn(modal, 'hide') + buttonEl.addEventListener('click', () => { + buttonEl.remove() + }) + + modalEl.addEventListener('shown.bs.modal', () => { + modalEl.dispatchEvent(createEvent('mousedown')) + buttonEl.click() + expect(spy).not.toHaveBeenCalled() + resolve() + }) + + modal.show() + }) + }) + + it('should do nothing is the modal is not shown', () => { + fixtureEl.innerHTML = '' + + const modalEl = fixtureEl.querySelector('.modal') + const modal = new Modal(modalEl) + + modal.hide() + + expect().nothing() + }) + + it('should do nothing is the modal is transitioning', () => { + fixtureEl.innerHTML = '' + + const modalEl = fixtureEl.querySelector('.modal') + const modal = new Modal(modalEl) + + modal._isTransitioning = true + modal.hide() + + expect().nothing() + }) + + it('should not hide a modal if hide is prevented', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = '' + + const modalEl = fixtureEl.querySelector('.modal') + const modal = new Modal(modalEl) + + modalEl.addEventListener('shown.bs.modal', () => { + modal.hide() + }) + + const hideCallback = () => { + setTimeout(() => { + expect(modal._isShown).toBeTrue() + resolve() + }, 10) + } + + modalEl.addEventListener('hide.bs.modal', event => { + event.preventDefault() + hideCallback() + }) + + modalEl.addEventListener('hidden.bs.modal', () => { + reject(new Error('should not trigger hidden')) + }) + + modal.show() + }) + }) + + it('should release focus trap', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const modalEl = fixtureEl.querySelector('.modal') + const modal = new Modal(modalEl) + const spy = spyOn(modal._focustrap, 'deactivate').and.callThrough() + + modalEl.addEventListener('shown.bs.modal', () => { + modal.hide() + }) + + modalEl.addEventListener('hidden.bs.modal', () => { + expect(spy).toHaveBeenCalled() + resolve() + }) + + modal.show() + }) + }) + }) + + describe('dispose', () => { + it('should dispose a modal', () => { + fixtureEl.innerHTML = '' + + const modalEl = fixtureEl.querySelector('.modal') + const modal = new Modal(modalEl) + const focustrap = modal._focustrap + const spyDeactivate = spyOn(focustrap, 'deactivate').and.callThrough() + + expect(Modal.getInstance(modalEl)).toEqual(modal) + + const spyOff = spyOn(EventHandler, 'off') + + modal.dispose() + + expect(Modal.getInstance(modalEl)).toBeNull() + expect(spyOff).toHaveBeenCalledTimes(3) + expect(spyDeactivate).toHaveBeenCalled() + }) + }) + + describe('handleUpdate', () => { + it('should call adjust dialog', () => { + fixtureEl.innerHTML = '' + + const modalEl = fixtureEl.querySelector('.modal') + const modal = new Modal(modalEl) + + const spy = spyOn(modal, '_adjustDialog') + + modal.handleUpdate() + + expect(spy).toHaveBeenCalled() + }) + }) + + describe('data-api', () => { + it('should toggle modal', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '' + ].join('') + + const modalEl = fixtureEl.querySelector('.modal') + const trigger = fixtureEl.querySelector('[data-bs-toggle="modal"]') + + modalEl.addEventListener('shown.bs.modal', () => { + expect(modalEl.getAttribute('aria-modal')).toEqual('true') + expect(modalEl.getAttribute('role')).toEqual('dialog') + expect(modalEl.getAttribute('aria-hidden')).toBeNull() + expect(modalEl.style.display).toEqual('block') + expect(document.querySelector('.modal-backdrop')).not.toBeNull() + setTimeout(() => trigger.click(), 10) + }) + + modalEl.addEventListener('hidden.bs.modal', () => { + expect(modalEl.getAttribute('aria-modal')).toBeNull() + expect(modalEl.getAttribute('role')).toBeNull() + expect(modalEl.getAttribute('aria-hidden')).toEqual('true') + expect(modalEl.style.display).toEqual('none') + expect(document.querySelector('.modal-backdrop')).toBeNull() + resolve() + }) + + trigger.click() + }) + }) + + it('should not recreate a new modal', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '' + ].join('') + + const modalEl = fixtureEl.querySelector('.modal') + const modal = new Modal(modalEl) + const trigger = fixtureEl.querySelector('[data-bs-toggle="modal"]') + + const spy = spyOn(modal, 'show').and.callThrough() + + modalEl.addEventListener('shown.bs.modal', () => { + expect(spy).toHaveBeenCalled() + resolve() + }) + + trigger.click() + }) + }) + + it('should prevent default when the trigger is or ', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '' + ].join('') + + const modalEl = fixtureEl.querySelector('.modal') + const trigger = fixtureEl.querySelector('[data-bs-toggle="modal"]') + + const spy = spyOn(Event.prototype, 'preventDefault').and.callThrough() + + modalEl.addEventListener('shown.bs.modal', () => { + expect(modalEl.getAttribute('aria-modal')).toEqual('true') + expect(modalEl.getAttribute('role')).toEqual('dialog') + expect(modalEl.getAttribute('aria-hidden')).toBeNull() + expect(modalEl.style.display).toEqual('block') + expect(document.querySelector('.modal-backdrop')).not.toBeNull() + expect(spy).toHaveBeenCalled() + resolve() + }) + + trigger.click() + }) + }) + + it('should focus the trigger on hide', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '' + ].join('') + + const modalEl = fixtureEl.querySelector('.modal') + const trigger = fixtureEl.querySelector('[data-bs-toggle="modal"]') + + const spy = spyOn(trigger, 'focus') + + modalEl.addEventListener('shown.bs.modal', () => { + const modal = Modal.getInstance(modalEl) + + modal.hide() + }) + + const hideListener = () => { + setTimeout(() => { + expect(spy).toHaveBeenCalled() + resolve() + }, 20) + } + + modalEl.addEventListener('hidden.bs.modal', () => { + hideListener() + }) + + trigger.click() + }) + }) + it('should not prevent default when a click occurred on data-bs-dismiss="modal" where tagName is DIFFERENT than or ', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const modalEl = fixtureEl.querySelector('.modal') + const btnClose = fixtureEl.querySelector('button[data-bs-dismiss="modal"]') + const modal = new Modal(modalEl) + + const spy = spyOn(Event.prototype, 'preventDefault').and.callThrough() + + modalEl.addEventListener('shown.bs.modal', () => { + btnClose.click() + }) + + modalEl.addEventListener('hidden.bs.modal', () => { + expect(spy).not.toHaveBeenCalled() + resolve() + }) + + modal.show() + }) + }) + + it('should prevent default when a click occurred on data-bs-dismiss="modal" where tagName is or ', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const modalEl = fixtureEl.querySelector('.modal') + const btnClose = fixtureEl.querySelector('a[data-bs-dismiss="modal"]') + const modal = new Modal(modalEl) + + const spy = spyOn(Event.prototype, 'preventDefault').and.callThrough() + + modalEl.addEventListener('shown.bs.modal', () => { + btnClose.click() + }) + + modalEl.addEventListener('hidden.bs.modal', () => { + expect(spy).toHaveBeenCalled() + resolve() + }) + + modal.show() + }) + }) + it('should not focus the trigger if the modal is not visible', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '' + ].join('') + + const modalEl = fixtureEl.querySelector('.modal') + const trigger = fixtureEl.querySelector('[data-bs-toggle="modal"]') + + const spy = spyOn(trigger, 'focus') + + modalEl.addEventListener('shown.bs.modal', () => { + const modal = Modal.getInstance(modalEl) + + modal.hide() + }) + + const hideListener = () => { + setTimeout(() => { + expect(spy).not.toHaveBeenCalled() + resolve() + }, 20) + } + + modalEl.addEventListener('hidden.bs.modal', () => { + hideListener() + }) + + trigger.click() + }) + }) + it('should not focus the trigger if the modal is not shown', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '' + ].join('') + + const modalEl = fixtureEl.querySelector('.modal') + const trigger = fixtureEl.querySelector('[data-bs-toggle="modal"]') + + const spy = spyOn(trigger, 'focus') + + const showListener = () => { + setTimeout(() => { + expect(spy).not.toHaveBeenCalled() + resolve() + }, 10) + } + + modalEl.addEventListener('show.bs.modal', event => { + event.preventDefault() + showListener() + }) + + trigger.click() + }) + }) + + it('should call hide first, if another modal is open', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '', + '' + ].join('') + + const trigger2 = fixtureEl.querySelector('button') + const modalEl1 = document.querySelector('#modal1') + const modalEl2 = document.querySelector('#modal2') + const modal1 = new Modal(modalEl1) + + modalEl1.addEventListener('shown.bs.modal', () => { + trigger2.click() + }) + modalEl1.addEventListener('hidden.bs.modal', () => { + expect(Modal.getInstance(modalEl2)).not.toBeNull() + expect(modalEl2).toHaveClass('show') + resolve() + }) + modal1.show() + }) + }) + }) + describe('jQueryInterface', () => { + it('should create a modal', () => { + fixtureEl.innerHTML = '' + + const div = fixtureEl.querySelector('div') + + jQueryMock.fn.modal = Modal.jQueryInterface + jQueryMock.elements = [div] + + jQueryMock.fn.modal.call(jQueryMock) + + expect(Modal.getInstance(div)).not.toBeNull() + }) + + it('should create a modal with given config', () => { + fixtureEl.innerHTML = '' + + const div = fixtureEl.querySelector('div') + + jQueryMock.fn.modal = Modal.jQueryInterface + jQueryMock.elements = [div] + + jQueryMock.fn.modal.call(jQueryMock, { keyboard: false }) + const spy = spyOn(Modal.prototype, 'constructor') + expect(spy).not.toHaveBeenCalledWith(div, { keyboard: false }) + + const modal = Modal.getInstance(div) + expect(modal).not.toBeNull() + expect(modal._config.keyboard).toBeFalse() + }) + + it('should not re create a modal', () => { + fixtureEl.innerHTML = '' + + const div = fixtureEl.querySelector('div') + const modal = new Modal(div) + + jQueryMock.fn.modal = Modal.jQueryInterface + jQueryMock.elements = [div] + + jQueryMock.fn.modal.call(jQueryMock) + + expect(Modal.getInstance(div)).toEqual(modal) + }) + + it('should throw error on undefined method', () => { + fixtureEl.innerHTML = '' + + const div = fixtureEl.querySelector('div') + const action = 'undefinedMethod' + + jQueryMock.fn.modal = Modal.jQueryInterface + jQueryMock.elements = [div] + + expect(() => { + jQueryMock.fn.modal.call(jQueryMock, action) + }).toThrowError(TypeError, `No method named "${action}"`) + }) + + it('should call show method', () => { + fixtureEl.innerHTML = '' + + const div = fixtureEl.querySelector('div') + const modal = new Modal(div) + + jQueryMock.fn.modal = Modal.jQueryInterface + jQueryMock.elements = [div] + + const spy = spyOn(modal, 'show') + + jQueryMock.fn.modal.call(jQueryMock, 'show') + + expect(spy).toHaveBeenCalled() + }) + + it('should not call show method', () => { + fixtureEl.innerHTML = '' + + const div = fixtureEl.querySelector('div') + + jQueryMock.fn.modal = Modal.jQueryInterface + jQueryMock.elements = [div] + + const spy = spyOn(Modal.prototype, 'show') + + jQueryMock.fn.modal.call(jQueryMock) + + expect(spy).not.toHaveBeenCalled() + }) + }) + + describe('getInstance', () => { + it('should return modal instance', () => { + fixtureEl.innerHTML = '' + + const div = fixtureEl.querySelector('div') + const modal = new Modal(div) + + expect(Modal.getInstance(div)).toEqual(modal) + expect(Modal.getInstance(div)).toBeInstanceOf(Modal) + }) + + it('should return null when there is no modal instance', () => { + fixtureEl.innerHTML = '' + + const div = fixtureEl.querySelector('div') + + expect(Modal.getInstance(div)).toBeNull() + }) + }) + + describe('getOrCreateInstance', () => { + it('should return modal instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const modal = new Modal(div) + + expect(Modal.getOrCreateInstance(div)).toEqual(modal) + expect(Modal.getInstance(div)).toEqual(Modal.getOrCreateInstance(div, {})) + expect(Modal.getOrCreateInstance(div)).toBeInstanceOf(Modal) + }) + + it('should return new instance when there is no modal instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(Modal.getInstance(div)).toBeNull() + expect(Modal.getOrCreateInstance(div)).toBeInstanceOf(Modal) + }) + + it('should return new instance when there is no modal instance with given configuration', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(Modal.getInstance(div)).toBeNull() + const modal = Modal.getOrCreateInstance(div, { + backdrop: true + }) + expect(modal).toBeInstanceOf(Modal) + + expect(modal._config.backdrop).toBeTrue() + }) + + it('should return the instance when exists without given configuration', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const modal = new Modal(div, { + backdrop: true + }) + expect(Modal.getInstance(div)).toEqual(modal) + + const modal2 = Modal.getOrCreateInstance(div, { + backdrop: false + }) + expect(modal).toBeInstanceOf(Modal) + expect(modal2).toEqual(modal) + + expect(modal2._config.backdrop).toBeTrue() + }) + }) +}) diff --git a/js/tests/unit/offcanvas.spec.js b/js/tests/unit/offcanvas.spec.js new file mode 100644 index 0000000..da2fb97 --- /dev/null +++ b/js/tests/unit/offcanvas.spec.js @@ -0,0 +1,912 @@ +import Offcanvas from '../../src/offcanvas' +import EventHandler from '../../src/dom/event-handler' +import { clearBodyAndDocument, clearFixture, createEvent, getFixture, jQueryMock } from '../helpers/fixture' +import { isVisible } from '../../src/util/index' +import ScrollBarHelper from '../../src/util/scrollbar' + +describe('Offcanvas', () => { + let fixtureEl + + beforeAll(() => { + fixtureEl = getFixture() + }) + + afterEach(() => { + clearFixture() + document.body.classList.remove('offcanvas-open') + clearBodyAndDocument() + }) + + beforeEach(() => { + clearBodyAndDocument() + }) + + describe('VERSION', () => { + it('should return plugin version', () => { + expect(Offcanvas.VERSION).toEqual(jasmine.any(String)) + }) + }) + + describe('Default', () => { + it('should return plugin default config', () => { + expect(Offcanvas.Default).toEqual(jasmine.any(Object)) + }) + }) + + describe('DATA_KEY', () => { + it('should return plugin data key', () => { + expect(Offcanvas.DATA_KEY).toEqual('bs.offcanvas') + }) + }) + + describe('constructor', () => { + it('should call hide when a element with data-bs-dismiss="offcanvas" is clicked', () => { + fixtureEl.innerHTML = [ + '
', + ' Close', + '
' + ].join('') + + const offCanvasEl = fixtureEl.querySelector('.offcanvas') + const closeEl = fixtureEl.querySelector('a') + const offCanvas = new Offcanvas(offCanvasEl) + + const spy = spyOn(offCanvas, 'hide') + + closeEl.click() + + expect(offCanvas._config.keyboard).toBeTrue() + expect(spy).toHaveBeenCalled() + }) + + it('should hide if esc is pressed', () => { + fixtureEl.innerHTML = '
' + + const offCanvasEl = fixtureEl.querySelector('.offcanvas') + const offCanvas = new Offcanvas(offCanvasEl) + const keyDownEsc = createEvent('keydown') + keyDownEsc.key = 'Escape' + + const spy = spyOn(offCanvas, 'hide') + + offCanvasEl.dispatchEvent(keyDownEsc) + + expect(spy).toHaveBeenCalled() + }) + + it('should hide if esc is pressed and backdrop is static', () => { + fixtureEl.innerHTML = '
' + + const offCanvasEl = fixtureEl.querySelector('.offcanvas') + const offCanvas = new Offcanvas(offCanvasEl, { backdrop: 'static' }) + const keyDownEsc = createEvent('keydown') + keyDownEsc.key = 'Escape' + + const spy = spyOn(offCanvas, 'hide') + + offCanvasEl.dispatchEvent(keyDownEsc) + + expect(spy).toHaveBeenCalled() + }) + + it('should not hide if esc is not pressed', () => { + fixtureEl.innerHTML = '
' + + const offCanvasEl = fixtureEl.querySelector('.offcanvas') + const offCanvas = new Offcanvas(offCanvasEl) + const keydownTab = createEvent('keydown') + keydownTab.key = 'Tab' + + const spy = spyOn(offCanvas, 'hide') + + offCanvasEl.dispatchEvent(keydownTab) + + expect(spy).not.toHaveBeenCalled() + }) + + it('should not hide if esc is pressed but with keyboard = false', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + + const offCanvasEl = fixtureEl.querySelector('.offcanvas') + const offCanvas = new Offcanvas(offCanvasEl, { keyboard: false }) + const keyDownEsc = createEvent('keydown') + keyDownEsc.key = 'Escape' + + const spy = spyOn(offCanvas, 'hide') + const hidePreventedSpy = jasmine.createSpy('hidePrevented') + offCanvasEl.addEventListener('hidePrevented.bs.offcanvas', hidePreventedSpy) + + offCanvasEl.addEventListener('shown.bs.offcanvas', () => { + expect(offCanvas._config.keyboard).toBeFalse() + offCanvasEl.dispatchEvent(keyDownEsc) + + expect(hidePreventedSpy).toHaveBeenCalled() + expect(spy).not.toHaveBeenCalled() + resolve() + }) + + offCanvas.show() + }) + }) + + it('should not hide if user clicks on static backdrop', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + + const offCanvasEl = fixtureEl.querySelector('div') + const offCanvas = new Offcanvas(offCanvasEl, { backdrop: 'static' }) + + const clickEvent = new Event('mousedown', { bubbles: true, cancelable: true }) + const spyClick = spyOn(offCanvas._backdrop._config, 'clickCallback').and.callThrough() + const spyHide = spyOn(offCanvas._backdrop, 'hide').and.callThrough() + const hidePreventedSpy = jasmine.createSpy('hidePrevented') + offCanvasEl.addEventListener('hidePrevented.bs.offcanvas', hidePreventedSpy) + + offCanvasEl.addEventListener('shown.bs.offcanvas', () => { + expect(spyClick).toEqual(jasmine.any(Function)) + + offCanvas._backdrop._getElement().dispatchEvent(clickEvent) + expect(hidePreventedSpy).toHaveBeenCalled() + expect(spyHide).not.toHaveBeenCalled() + resolve() + }) + + offCanvas.show() + }) + }) + + it('should call `hide` on resize, if element\'s position is not fixed any more', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + + const offCanvasEl = fixtureEl.querySelector('div') + const offCanvas = new Offcanvas(offCanvasEl) + + const spy = spyOn(offCanvas, 'hide').and.callThrough() + + offCanvasEl.addEventListener('shown.bs.offcanvas', () => { + const resizeEvent = createEvent('resize') + offCanvasEl.style.removeProperty('position') + + window.dispatchEvent(resizeEvent) + expect(spy).toHaveBeenCalled() + resolve() + }) + + offCanvas.show() + }) + }) + }) + + describe('config', () => { + it('should have default values', () => { + fixtureEl.innerHTML = '
' + + const offCanvasEl = fixtureEl.querySelector('.offcanvas') + const offCanvas = new Offcanvas(offCanvasEl) + + expect(offCanvas._config.backdrop).toBeTrue() + expect(offCanvas._backdrop._config.isVisible).toBeTrue() + expect(offCanvas._config.keyboard).toBeTrue() + expect(offCanvas._config.scroll).toBeFalse() + }) + + it('should read data attributes and override default config', () => { + fixtureEl.innerHTML = '
' + + const offCanvasEl = fixtureEl.querySelector('.offcanvas') + const offCanvas = new Offcanvas(offCanvasEl) + + expect(offCanvas._config.backdrop).toBeFalse() + expect(offCanvas._backdrop._config.isVisible).toBeFalse() + expect(offCanvas._config.keyboard).toBeFalse() + expect(offCanvas._config.scroll).toBeTrue() + }) + + it('given a config object must override data attributes', () => { + fixtureEl.innerHTML = '
' + + const offCanvasEl = fixtureEl.querySelector('.offcanvas') + const offCanvas = new Offcanvas(offCanvasEl, { + backdrop: true, + keyboard: true, + scroll: false + }) + expect(offCanvas._config.backdrop).toBeTrue() + expect(offCanvas._config.keyboard).toBeTrue() + expect(offCanvas._config.scroll).toBeFalse() + }) + }) + + describe('options', () => { + it('if scroll is enabled, should allow body to scroll while offcanvas is open', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + + const spyHide = spyOn(ScrollBarHelper.prototype, 'hide').and.callThrough() + const spyReset = spyOn(ScrollBarHelper.prototype, 'reset').and.callThrough() + const offCanvasEl = fixtureEl.querySelector('.offcanvas') + const offCanvas = new Offcanvas(offCanvasEl, { scroll: true }) + + offCanvasEl.addEventListener('shown.bs.offcanvas', () => { + expect(spyHide).not.toHaveBeenCalled() + offCanvas.hide() + }) + offCanvasEl.addEventListener('hidden.bs.offcanvas', () => { + expect(spyReset).not.toHaveBeenCalled() + resolve() + }) + offCanvas.show() + }) + }) + + it('if scroll is disabled, should call ScrollBarHelper to handle scrollBar on body', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + + const spyHide = spyOn(ScrollBarHelper.prototype, 'hide').and.callThrough() + const spyReset = spyOn(ScrollBarHelper.prototype, 'reset').and.callThrough() + const offCanvasEl = fixtureEl.querySelector('.offcanvas') + const offCanvas = new Offcanvas(offCanvasEl, { scroll: false }) + + offCanvasEl.addEventListener('shown.bs.offcanvas', () => { + expect(spyHide).toHaveBeenCalled() + offCanvas.hide() + }) + offCanvasEl.addEventListener('hidden.bs.offcanvas', () => { + expect(spyReset).toHaveBeenCalled() + resolve() + }) + offCanvas.show() + }) + }) + + it('should hide a shown element if user click on backdrop', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + + const offCanvasEl = fixtureEl.querySelector('div') + const offCanvas = new Offcanvas(offCanvasEl, { backdrop: true }) + + const clickEvent = new Event('mousedown', { bubbles: true, cancelable: true }) + const spy = spyOn(offCanvas._backdrop._config, 'clickCallback').and.callThrough() + + offCanvasEl.addEventListener('shown.bs.offcanvas', () => { + expect(offCanvas._backdrop._config.clickCallback).toEqual(jasmine.any(Function)) + + offCanvas._backdrop._getElement().dispatchEvent(clickEvent) + }) + + offCanvasEl.addEventListener('hidden.bs.offcanvas', () => { + expect(spy).toHaveBeenCalled() + resolve() + }) + + offCanvas.show() + }) + }) + + it('should not trap focus if scroll is allowed', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + + const offCanvasEl = fixtureEl.querySelector('.offcanvas') + const offCanvas = new Offcanvas(offCanvasEl, { + scroll: true, + backdrop: false + }) + + const spy = spyOn(offCanvas._focustrap, 'activate').and.callThrough() + + offCanvasEl.addEventListener('shown.bs.offcanvas', () => { + expect(spy).not.toHaveBeenCalled() + resolve() + }) + + offCanvas.show() + }) + }) + + it('should trap focus if scroll is allowed OR backdrop is enabled', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + + const offCanvasEl = fixtureEl.querySelector('.offcanvas') + const offCanvas = new Offcanvas(offCanvasEl, { + scroll: true, + backdrop: true + }) + + const spy = spyOn(offCanvas._focustrap, 'activate').and.callThrough() + + offCanvasEl.addEventListener('shown.bs.offcanvas', () => { + expect(spy).toHaveBeenCalled() + resolve() + }) + + offCanvas.show() + }) + }) + }) + + describe('toggle', () => { + it('should call show method if show class is not present', () => { + fixtureEl.innerHTML = '
' + + const offCanvasEl = fixtureEl.querySelector('.offcanvas') + const offCanvas = new Offcanvas(offCanvasEl) + + const spy = spyOn(offCanvas, 'show') + + offCanvas.toggle() + + expect(spy).toHaveBeenCalled() + }) + + it('should call hide method if show class is present', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + + const offCanvasEl = fixtureEl.querySelector('.offcanvas') + const offCanvas = new Offcanvas(offCanvasEl) + + offCanvasEl.addEventListener('shown.bs.offcanvas', () => { + expect(offCanvasEl).toHaveClass('show') + const spy = spyOn(offCanvas, 'hide') + + offCanvas.toggle() + + expect(spy).toHaveBeenCalled() + resolve() + }) + + offCanvas.show() + }) + }) + }) + + describe('show', () => { + it('should add `showing` class during opening and `show` class on end', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + const offCanvasEl = fixtureEl.querySelector('.offcanvas') + const offCanvas = new Offcanvas(offCanvasEl) + + offCanvasEl.addEventListener('show.bs.offcanvas', () => { + expect(offCanvasEl).not.toHaveClass('show') + }) + + offCanvasEl.addEventListener('shown.bs.offcanvas', () => { + expect(offCanvasEl).not.toHaveClass('showing') + expect(offCanvasEl).toHaveClass('show') + resolve() + }) + + offCanvas.show() + expect(offCanvasEl).toHaveClass('showing') + }) + }) + + it('should do nothing if already shown', () => { + fixtureEl.innerHTML = '
' + + const offCanvasEl = fixtureEl.querySelector('div') + const offCanvas = new Offcanvas(offCanvasEl) + offCanvas.show() + + expect(offCanvasEl).toHaveClass('show') + + const spyShow = spyOn(offCanvas._backdrop, 'show').and.callThrough() + const spyTrigger = spyOn(EventHandler, 'trigger').and.callThrough() + offCanvas.show() + + expect(spyTrigger).not.toHaveBeenCalled() + expect(spyShow).not.toHaveBeenCalled() + }) + + it('should show a hidden element', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + + const offCanvasEl = fixtureEl.querySelector('div') + const offCanvas = new Offcanvas(offCanvasEl) + const spy = spyOn(offCanvas._backdrop, 'show').and.callThrough() + + offCanvasEl.addEventListener('shown.bs.offcanvas', () => { + expect(offCanvasEl).toHaveClass('show') + expect(spy).toHaveBeenCalled() + resolve() + }) + + offCanvas.show() + }) + }) + + it('should not fire shown when show is prevented', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = '
' + + const offCanvasEl = fixtureEl.querySelector('div') + const offCanvas = new Offcanvas(offCanvasEl) + const spy = spyOn(offCanvas._backdrop, 'show').and.callThrough() + + const expectEnd = () => { + setTimeout(() => { + expect(spy).not.toHaveBeenCalled() + resolve() + }, 10) + } + + offCanvasEl.addEventListener('show.bs.offcanvas', event => { + event.preventDefault() + expectEnd() + }) + + offCanvasEl.addEventListener('shown.bs.offcanvas', () => { + reject(new Error('should not fire shown event')) + }) + + offCanvas.show() + }) + }) + + it('on window load, should make visible an offcanvas element, if its markup contains class "show"', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + + const offCanvasEl = fixtureEl.querySelector('div') + const spy = spyOn(Offcanvas.prototype, 'show').and.callThrough() + + offCanvasEl.addEventListener('shown.bs.offcanvas', () => { + resolve() + }) + + window.dispatchEvent(createEvent('load')) + + const instance = Offcanvas.getInstance(offCanvasEl) + expect(instance).not.toBeNull() + expect(spy).toHaveBeenCalled() + }) + }) + + it('should trap focus', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + + const offCanvasEl = fixtureEl.querySelector('.offcanvas') + const offCanvas = new Offcanvas(offCanvasEl) + + const spy = spyOn(offCanvas._focustrap, 'activate').and.callThrough() + + offCanvasEl.addEventListener('shown.bs.offcanvas', () => { + expect(spy).toHaveBeenCalled() + resolve() + }) + + offCanvas.show() + }) + }) + }) + + describe('hide', () => { + it('should add `hiding` class during closing and remover `show` & `hiding` classes on end', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + const offCanvasEl = fixtureEl.querySelector('.offcanvas') + const offCanvas = new Offcanvas(offCanvasEl) + + offCanvasEl.addEventListener('hide.bs.offcanvas', () => { + expect(offCanvasEl).not.toHaveClass('showing') + expect(offCanvasEl).toHaveClass('show') + }) + + offCanvasEl.addEventListener('hidden.bs.offcanvas', () => { + expect(offCanvasEl).not.toHaveClass('hiding') + expect(offCanvasEl).not.toHaveClass('show') + resolve() + }) + + offCanvas.show() + offCanvasEl.addEventListener('shown.bs.offcanvas', () => { + offCanvas.hide() + expect(offCanvasEl).not.toHaveClass('showing') + expect(offCanvasEl).toHaveClass('hiding') + }) + }) + }) + + it('should do nothing if already shown', () => { + fixtureEl.innerHTML = '
' + + const spyTrigger = spyOn(EventHandler, 'trigger').and.callThrough() + + const offCanvasEl = fixtureEl.querySelector('div') + const offCanvas = new Offcanvas(offCanvasEl) + const spyHide = spyOn(offCanvas._backdrop, 'hide').and.callThrough() + + offCanvas.hide() + expect(spyHide).not.toHaveBeenCalled() + expect(spyTrigger).not.toHaveBeenCalled() + }) + + it('should hide a shown element', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + + const offCanvasEl = fixtureEl.querySelector('div') + const offCanvas = new Offcanvas(offCanvasEl) + const spy = spyOn(offCanvas._backdrop, 'hide').and.callThrough() + offCanvas.show() + + offCanvasEl.addEventListener('hidden.bs.offcanvas', () => { + expect(offCanvasEl).not.toHaveClass('show') + expect(spy).toHaveBeenCalled() + resolve() + }) + + offCanvas.hide() + }) + }) + + it('should not fire hidden when hide is prevented', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = '
' + + const offCanvasEl = fixtureEl.querySelector('div') + const offCanvas = new Offcanvas(offCanvasEl) + const spy = spyOn(offCanvas._backdrop, 'hide').and.callThrough() + + offCanvas.show() + + const expectEnd = () => { + setTimeout(() => { + expect(spy).not.toHaveBeenCalled() + resolve() + }, 10) + } + + offCanvasEl.addEventListener('hide.bs.offcanvas', event => { + event.preventDefault() + expectEnd() + }) + + offCanvasEl.addEventListener('hidden.bs.offcanvas', () => { + reject(new Error('should not fire hidden event')) + }) + + offCanvas.hide() + }) + }) + + it('should release focus trap', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + + const offCanvasEl = fixtureEl.querySelector('div') + const offCanvas = new Offcanvas(offCanvasEl) + const spy = spyOn(offCanvas._focustrap, 'deactivate').and.callThrough() + offCanvas.show() + + offCanvasEl.addEventListener('hidden.bs.offcanvas', () => { + expect(spy).toHaveBeenCalled() + resolve() + }) + + offCanvas.hide() + }) + }) + }) + + describe('dispose', () => { + it('should dispose an offcanvas', () => { + fixtureEl.innerHTML = '
' + + const offCanvasEl = fixtureEl.querySelector('div') + const offCanvas = new Offcanvas(offCanvasEl) + const backdrop = offCanvas._backdrop + const spyDispose = spyOn(backdrop, 'dispose').and.callThrough() + const focustrap = offCanvas._focustrap + const spyDeactivate = spyOn(focustrap, 'deactivate').and.callThrough() + + expect(Offcanvas.getInstance(offCanvasEl)).toEqual(offCanvas) + + offCanvas.dispose() + + expect(spyDispose).toHaveBeenCalled() + expect(offCanvas._backdrop).toBeNull() + expect(spyDeactivate).toHaveBeenCalled() + expect(offCanvas._focustrap).toBeNull() + expect(Offcanvas.getInstance(offCanvasEl)).toBeNull() + }) + }) + + describe('data-api', () => { + it('should not prevent event for input', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '
' + ].join('') + + const target = fixtureEl.querySelector('input') + const offCanvasEl = fixtureEl.querySelector('#offcanvasdiv1') + + offCanvasEl.addEventListener('shown.bs.offcanvas', () => { + expect(offCanvasEl).toHaveClass('show') + expect(target.checked).toBeTrue() + resolve() + }) + + target.click() + }) + }) + + it('should not call toggle on disabled elements', () => { + fixtureEl.innerHTML = [ + '', + '
' + ].join('') + + const target = fixtureEl.querySelector('a') + + const spy = spyOn(Offcanvas.prototype, 'toggle') + + target.click() + + expect(spy).not.toHaveBeenCalled() + }) + + it('should call hide first, if another offcanvas is open', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '
', + '
' + ].join('') + + const trigger2 = fixtureEl.querySelector('#btn2') + const offcanvasEl1 = document.querySelector('#offcanvas1') + const offcanvasEl2 = document.querySelector('#offcanvas2') + const offcanvas1 = new Offcanvas(offcanvasEl1) + + offcanvasEl1.addEventListener('shown.bs.offcanvas', () => { + trigger2.click() + }) + offcanvasEl1.addEventListener('hidden.bs.offcanvas', () => { + expect(Offcanvas.getInstance(offcanvasEl2)).not.toBeNull() + resolve() + }) + offcanvas1.show() + }) + }) + + it('should focus on trigger element after closing offcanvas', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '
' + ].join('') + + const trigger = fixtureEl.querySelector('#btn') + const offcanvasEl = fixtureEl.querySelector('#offcanvas') + const offcanvas = new Offcanvas(offcanvasEl) + const spy = spyOn(trigger, 'focus') + + offcanvasEl.addEventListener('shown.bs.offcanvas', () => { + offcanvas.hide() + }) + offcanvasEl.addEventListener('hidden.bs.offcanvas', () => { + setTimeout(() => { + expect(spy).toHaveBeenCalled() + resolve() + }, 5) + }) + + trigger.click() + }) + }) + + it('should not focus on trigger element after closing offcanvas, if it is not visible', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '
' + ].join('') + + const trigger = fixtureEl.querySelector('#btn') + const offcanvasEl = fixtureEl.querySelector('#offcanvas') + const offcanvas = new Offcanvas(offcanvasEl) + const spy = spyOn(trigger, 'focus') + + offcanvasEl.addEventListener('shown.bs.offcanvas', () => { + trigger.style.display = 'none' + offcanvas.hide() + }) + offcanvasEl.addEventListener('hidden.bs.offcanvas', () => { + setTimeout(() => { + expect(isVisible(trigger)).toBeFalse() + expect(spy).not.toHaveBeenCalled() + resolve() + }, 5) + }) + + trigger.click() + }) + }) + }) + + describe('jQueryInterface', () => { + it('should create an offcanvas', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + jQueryMock.fn.offcanvas = Offcanvas.jQueryInterface + jQueryMock.elements = [div] + + jQueryMock.fn.offcanvas.call(jQueryMock) + + expect(Offcanvas.getInstance(div)).not.toBeNull() + }) + + it('should not re create an offcanvas', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const offCanvas = new Offcanvas(div) + + jQueryMock.fn.offcanvas = Offcanvas.jQueryInterface + jQueryMock.elements = [div] + + jQueryMock.fn.offcanvas.call(jQueryMock) + + expect(Offcanvas.getInstance(div)).toEqual(offCanvas) + }) + + it('should throw error on undefined method', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const action = 'undefinedMethod' + + jQueryMock.fn.offcanvas = Offcanvas.jQueryInterface + jQueryMock.elements = [div] + + expect(() => { + jQueryMock.fn.offcanvas.call(jQueryMock, action) + }).toThrowError(TypeError, `No method named "${action}"`) + }) + + it('should throw error on protected method', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const action = '_getConfig' + + jQueryMock.fn.offcanvas = Offcanvas.jQueryInterface + jQueryMock.elements = [div] + + expect(() => { + jQueryMock.fn.offcanvas.call(jQueryMock, action) + }).toThrowError(TypeError, `No method named "${action}"`) + }) + + it('should throw error if method "constructor" is being called', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const action = 'constructor' + + jQueryMock.fn.offcanvas = Offcanvas.jQueryInterface + jQueryMock.elements = [div] + + expect(() => { + jQueryMock.fn.offcanvas.call(jQueryMock, action) + }).toThrowError(TypeError, `No method named "${action}"`) + }) + + it('should call offcanvas method', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + const spy = spyOn(Offcanvas.prototype, 'show') + + jQueryMock.fn.offcanvas = Offcanvas.jQueryInterface + jQueryMock.elements = [div] + + jQueryMock.fn.offcanvas.call(jQueryMock, 'show') + expect(spy).toHaveBeenCalled() + }) + + it('should create a offcanvas with given config', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + jQueryMock.fn.offcanvas = Offcanvas.jQueryInterface + jQueryMock.elements = [div] + + jQueryMock.fn.offcanvas.call(jQueryMock, { scroll: true }) + + const offcanvas = Offcanvas.getInstance(div) + expect(offcanvas).not.toBeNull() + expect(offcanvas._config.scroll).toBeTrue() + }) + }) + + describe('getInstance', () => { + it('should return offcanvas instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const offCanvas = new Offcanvas(div) + + expect(Offcanvas.getInstance(div)).toEqual(offCanvas) + expect(Offcanvas.getInstance(div)).toBeInstanceOf(Offcanvas) + }) + + it('should return null when there is no offcanvas instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(Offcanvas.getInstance(div)).toBeNull() + }) + }) + + describe('getOrCreateInstance', () => { + it('should return offcanvas instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const offcanvas = new Offcanvas(div) + + expect(Offcanvas.getOrCreateInstance(div)).toEqual(offcanvas) + expect(Offcanvas.getInstance(div)).toEqual(Offcanvas.getOrCreateInstance(div, {})) + expect(Offcanvas.getOrCreateInstance(div)).toBeInstanceOf(Offcanvas) + }) + + it('should return new instance when there is no Offcanvas instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(Offcanvas.getInstance(div)).toBeNull() + expect(Offcanvas.getOrCreateInstance(div)).toBeInstanceOf(Offcanvas) + }) + + it('should return new instance when there is no offcanvas instance with given configuration', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(Offcanvas.getInstance(div)).toBeNull() + const offcanvas = Offcanvas.getOrCreateInstance(div, { + scroll: true + }) + expect(offcanvas).toBeInstanceOf(Offcanvas) + + expect(offcanvas._config.scroll).toBeTrue() + }) + + it('should return the instance when exists without given configuration', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const offcanvas = new Offcanvas(div, { + scroll: true + }) + expect(Offcanvas.getInstance(div)).toEqual(offcanvas) + + const offcanvas2 = Offcanvas.getOrCreateInstance(div, { + scroll: false + }) + expect(offcanvas).toBeInstanceOf(Offcanvas) + expect(offcanvas2).toEqual(offcanvas) + + expect(offcanvas2._config.scroll).toBeTrue() + }) + }) +}) diff --git a/js/tests/unit/popover.spec.js b/js/tests/unit/popover.spec.js new file mode 100644 index 0000000..baf691c --- /dev/null +++ b/js/tests/unit/popover.spec.js @@ -0,0 +1,413 @@ +import Popover from '../../src/popover' +import EventHandler from '../../src/dom/event-handler' +import { clearFixture, getFixture, jQueryMock } from '../helpers/fixture' + +describe('Popover', () => { + let fixtureEl + + beforeAll(() => { + fixtureEl = getFixture() + }) + + afterEach(() => { + clearFixture() + + const popoverList = document.querySelectorAll('.popover') + + for (const popoverEl of popoverList) { + popoverEl.remove() + } + }) + + describe('VERSION', () => { + it('should return plugin version', () => { + expect(Popover.VERSION).toEqual(jasmine.any(String)) + }) + }) + + describe('Default', () => { + it('should return plugin default config', () => { + expect(Popover.Default).toEqual(jasmine.any(Object)) + }) + }) + + describe('NAME', () => { + it('should return plugin name', () => { + expect(Popover.NAME).toEqual(jasmine.any(String)) + }) + }) + + describe('DATA_KEY', () => { + it('should return plugin data key', () => { + expect(Popover.DATA_KEY).toEqual('bs.popover') + }) + }) + + describe('EVENT_KEY', () => { + it('should return plugin event key', () => { + expect(Popover.EVENT_KEY).toEqual('.bs.popover') + }) + }) + + describe('DefaultType', () => { + it('should return plugin default type', () => { + expect(Popover.DefaultType).toEqual(jasmine.any(Object)) + }) + }) + + describe('show', () => { + it('should show a popover', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = 'BS twitter' + + const popoverEl = fixtureEl.querySelector('a') + const popover = new Popover(popoverEl) + + popoverEl.addEventListener('shown.bs.popover', () => { + expect(document.querySelector('.popover')).not.toBeNull() + resolve() + }) + + popover.show() + }) + }) + + it('should set title and content from functions', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = 'BS twitter' + + const popoverEl = fixtureEl.querySelector('a') + const popover = new Popover(popoverEl, { + title: () => 'Bootstrap', + content: () => 'loves writing tests (╯°□°)╯︵ ┻━┻' + }) + + popoverEl.addEventListener('shown.bs.popover', () => { + const popoverDisplayed = document.querySelector('.popover') + + expect(popoverDisplayed).not.toBeNull() + expect(popoverDisplayed.querySelector('.popover-header').textContent).toEqual('Bootstrap') + expect(popoverDisplayed.querySelector('.popover-body').textContent).toEqual('loves writing tests (╯°□°)╯︵ ┻━┻') + resolve() + }) + + popover.show() + }) + }) + + it('should show a popover with just content without having header', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = 'Nice link' + + const popoverEl = fixtureEl.querySelector('a') + const popover = new Popover(popoverEl, { + content: 'Some beautiful content :)' + }) + + popoverEl.addEventListener('shown.bs.popover', () => { + const popoverDisplayed = document.querySelector('.popover') + + expect(popoverDisplayed).not.toBeNull() + expect(popoverDisplayed.querySelector('.popover-header')).toBeNull() + expect(popoverDisplayed.querySelector('.popover-body').textContent).toEqual('Some beautiful content :)') + resolve() + }) + + popover.show() + }) + }) + + it('should show a popover with just title without having body', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = 'Nice link' + + const popoverEl = fixtureEl.querySelector('a') + const popover = new Popover(popoverEl, { + title: 'Title which does not require content' + }) + + popoverEl.addEventListener('shown.bs.popover', () => { + const popoverDisplayed = document.querySelector('.popover') + + expect(popoverDisplayed).not.toBeNull() + expect(popoverDisplayed.querySelector('.popover-body')).toBeNull() + expect(popoverDisplayed.querySelector('.popover-header').textContent).toEqual('Title which does not require content') + resolve() + }) + + popover.show() + }) + }) + + it('should show a popover with just title without having body using data-attribute to get config', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = 'Nice link' + + const popoverEl = fixtureEl.querySelector('a') + const popover = new Popover(popoverEl) + + popoverEl.addEventListener('shown.bs.popover', () => { + const popoverDisplayed = document.querySelector('.popover') + + expect(popoverDisplayed).not.toBeNull() + expect(popoverDisplayed.querySelector('.popover-body')).toBeNull() + expect(popoverDisplayed.querySelector('.popover-header').textContent).toEqual('Title which does not require content') + resolve() + }) + + popover.show() + }) + }) + + it('should NOT show a popover without `title` and `content`', () => { + fixtureEl.innerHTML = 'Nice link' + + const popoverEl = fixtureEl.querySelector('a') + const popover = new Popover(popoverEl, { animation: false }) + const spy = spyOn(EventHandler, 'trigger').and.callThrough() + + popover.show() + + expect(spy).not.toHaveBeenCalledWith(popoverEl, Popover.eventName('show')) + expect(document.querySelector('.popover')).toBeNull() + }) + + it('"setContent" should keep the initial template', () => { + fixtureEl.innerHTML = 'BS twitter' + + const popoverEl = fixtureEl.querySelector('a') + const popover = new Popover(popoverEl) + + popover.setContent({ '.tooltip-inner': 'foo' }) + const tip = popover._getTipElement() + + expect(tip).toHaveClass('popover') + expect(tip).toHaveClass('bs-popover-auto') + expect(tip.querySelector('.popover-arrow')).not.toBeNull() + expect(tip.querySelector('.popover-header')).not.toBeNull() + expect(tip.querySelector('.popover-body')).not.toBeNull() + }) + + it('should call setContent once', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = 'BS twitter' + + const popoverEl = fixtureEl.querySelector('a') + const popover = new Popover(popoverEl, { + content: 'Popover content' + }) + expect(popover._templateFactory).toBeNull() + let spy = null + let times = 1 + + popoverEl.addEventListener('hidden.bs.popover', () => { + popover.show() + }) + + popoverEl.addEventListener('shown.bs.popover', () => { + spy = spy || spyOn(popover._templateFactory, 'constructor').and.callThrough() + const popoverDisplayed = document.querySelector('.popover') + + expect(popoverDisplayed).not.toBeNull() + expect(popoverDisplayed.querySelector('.popover-body').textContent).toEqual('Popover content') + expect(spy).toHaveBeenCalledTimes(0) + if (times > 1) { + resolve() + } + + times++ + popover.hide() + }) + popover.show() + }) + }) + + it('should show a popover with provided custom class', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = 'BS twitter' + + const popoverEl = fixtureEl.querySelector('a') + const popover = new Popover(popoverEl) + + popoverEl.addEventListener('shown.bs.popover', () => { + const tip = document.querySelector('.popover') + expect(tip).not.toBeNull() + expect(tip).toHaveClass('custom-class') + resolve() + }) + + popover.show() + }) + }) + }) + + describe('hide', () => { + it('should hide a popover', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = 'BS twitter' + + const popoverEl = fixtureEl.querySelector('a') + const popover = new Popover(popoverEl) + + popoverEl.addEventListener('shown.bs.popover', () => { + popover.hide() + }) + + popoverEl.addEventListener('hidden.bs.popover', () => { + expect(document.querySelector('.popover')).toBeNull() + resolve() + }) + + popover.show() + }) + }) + }) + + describe('jQueryInterface', () => { + it('should create a popover', () => { + fixtureEl.innerHTML = 'BS twitter' + + const popoverEl = fixtureEl.querySelector('a') + + jQueryMock.fn.popover = Popover.jQueryInterface + jQueryMock.elements = [popoverEl] + + jQueryMock.fn.popover.call(jQueryMock) + + expect(Popover.getInstance(popoverEl)).not.toBeNull() + }) + + it('should create a popover with a config object', () => { + fixtureEl.innerHTML = 'BS twitter' + + const popoverEl = fixtureEl.querySelector('a') + + jQueryMock.fn.popover = Popover.jQueryInterface + jQueryMock.elements = [popoverEl] + + jQueryMock.fn.popover.call(jQueryMock, { + content: 'Popover content' + }) + + expect(Popover.getInstance(popoverEl)).not.toBeNull() + }) + + it('should not re create a popover', () => { + fixtureEl.innerHTML = 'BS twitter' + + const popoverEl = fixtureEl.querySelector('a') + const popover = new Popover(popoverEl) + + jQueryMock.fn.popover = Popover.jQueryInterface + jQueryMock.elements = [popoverEl] + + jQueryMock.fn.popover.call(jQueryMock) + + expect(Popover.getInstance(popoverEl)).toEqual(popover) + }) + + it('should throw error on undefined method', () => { + fixtureEl.innerHTML = 'BS twitter' + + const popoverEl = fixtureEl.querySelector('a') + const action = 'undefinedMethod' + + jQueryMock.fn.popover = Popover.jQueryInterface + jQueryMock.elements = [popoverEl] + + expect(() => { + jQueryMock.fn.popover.call(jQueryMock, action) + }).toThrowError(TypeError, `No method named "${action}"`) + }) + + it('should should call show method', () => { + fixtureEl.innerHTML = 'BS twitter' + + const popoverEl = fixtureEl.querySelector('a') + const popover = new Popover(popoverEl) + + jQueryMock.fn.popover = Popover.jQueryInterface + jQueryMock.elements = [popoverEl] + + const spy = spyOn(popover, 'show') + + jQueryMock.fn.popover.call(jQueryMock, 'show') + + expect(spy).toHaveBeenCalled() + }) + }) + + describe('getInstance', () => { + it('should return popover instance', () => { + fixtureEl.innerHTML = 'BS twitter' + + const popoverEl = fixtureEl.querySelector('a') + const popover = new Popover(popoverEl) + + expect(Popover.getInstance(popoverEl)).toEqual(popover) + expect(Popover.getInstance(popoverEl)).toBeInstanceOf(Popover) + }) + + it('should return null when there is no popover instance', () => { + fixtureEl.innerHTML = 'BS twitter' + + const popoverEl = fixtureEl.querySelector('a') + + expect(Popover.getInstance(popoverEl)).toBeNull() + }) + }) + + describe('getOrCreateInstance', () => { + it('should return popover instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const popover = new Popover(div) + + expect(Popover.getOrCreateInstance(div)).toEqual(popover) + expect(Popover.getInstance(div)).toEqual(Popover.getOrCreateInstance(div, {})) + expect(Popover.getOrCreateInstance(div)).toBeInstanceOf(Popover) + }) + + it('should return new instance when there is no popover instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(Popover.getInstance(div)).toBeNull() + expect(Popover.getOrCreateInstance(div)).toBeInstanceOf(Popover) + }) + + it('should return new instance when there is no popover instance with given configuration', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(Popover.getInstance(div)).toBeNull() + const popover = Popover.getOrCreateInstance(div, { + placement: 'top' + }) + expect(popover).toBeInstanceOf(Popover) + + expect(popover._config.placement).toEqual('top') + }) + + it('should return the instance when exists without given configuration', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const popover = new Popover(div, { + placement: 'top' + }) + expect(Popover.getInstance(div)).toEqual(popover) + + const popover2 = Popover.getOrCreateInstance(div, { + placement: 'bottom' + }) + expect(popover).toBeInstanceOf(Popover) + expect(popover2).toEqual(popover) + + expect(popover2._config.placement).toEqual('top') + }) + }) +}) diff --git a/js/tests/unit/scrollspy.spec.js b/js/tests/unit/scrollspy.spec.js new file mode 100644 index 0000000..c7951e6 --- /dev/null +++ b/js/tests/unit/scrollspy.spec.js @@ -0,0 +1,946 @@ +import ScrollSpy from '../../src/scrollspy' + +/** Test helpers */ +import { clearFixture, createEvent, getFixture, jQueryMock } from '../helpers/fixture' +import EventHandler from '../../src/dom/event-handler' + +describe('ScrollSpy', () => { + let fixtureEl + + const getElementScrollSpy = element => element.scrollTo ? + spyOn(element, 'scrollTo').and.callThrough() : + spyOnProperty(element, 'scrollTop', 'set').and.callThrough() + + const scrollTo = (el, height) => { + el.scrollTop = height + } + + const onScrollStop = (callback, element, timeout = 30) => { + let handle = null + const onScroll = function () { + if (handle) { + window.clearTimeout(handle) + } + + handle = setTimeout(() => { + element.removeEventListener('scroll', onScroll) + callback() + }, timeout + 1) + } + + element.addEventListener('scroll', onScroll) + } + + const getDummyFixture = () => { + return [ + '', + '
', + '
div 1
', + '
' + ].join('') + } + + const testElementIsActiveAfterScroll = ({ elementSelector, targetSelector, contentEl, scrollSpy, cb }) => { + const element = fixtureEl.querySelector(elementSelector) + const target = fixtureEl.querySelector(targetSelector) + // add top padding to fix Chrome on Android failures + const paddingTop = 0 + const parentOffset = getComputedStyle(contentEl).getPropertyValue('position') === 'relative' ? 0 : contentEl.offsetTop + const scrollHeight = (target.offsetTop - parentOffset) + paddingTop + + contentEl.addEventListener('activate.bs.scrollspy', event => { + if (scrollSpy._activeTarget !== element) { + return + } + + expect(element).toHaveClass('active') + expect(scrollSpy._activeTarget).toEqual(element) + expect(event.relatedTarget).toEqual(element) + cb() + }) + + setTimeout(() => { // in case we scroll something before the test + scrollTo(contentEl, scrollHeight) + }, 100) + } + + beforeAll(() => { + fixtureEl = getFixture() + }) + + afterEach(() => { + clearFixture() + }) + + describe('VERSION', () => { + it('should return plugin version', () => { + expect(ScrollSpy.VERSION).toEqual(jasmine.any(String)) + }) + }) + + describe('Default', () => { + it('should return plugin default config', () => { + expect(ScrollSpy.Default).toEqual(jasmine.any(Object)) + }) + }) + + describe('DATA_KEY', () => { + it('should return plugin data key', () => { + expect(ScrollSpy.DATA_KEY).toEqual('bs.scrollspy') + }) + }) + + describe('constructor', () => { + it('should take care of element either passed as a CSS selector or DOM element', () => { + fixtureEl.innerHTML = getDummyFixture() + + const sSpyEl = fixtureEl.querySelector('.content') + const sSpyBySelector = new ScrollSpy('.content') + const sSpyByElement = new ScrollSpy(sSpyEl) + + expect(sSpyBySelector._element).toEqual(sSpyEl) + expect(sSpyByElement._element).toEqual(sSpyEl) + }) + + it('should null, if element is not scrollable', () => { + fixtureEl.innerHTML = [ + '', + '
', + '
test
', + '
' + ].join('') + + const scrollSpy = new ScrollSpy(fixtureEl.querySelector('#content'), { + target: '#navigation' + }) + + expect(scrollSpy._observer.root).toBeNull() + expect(scrollSpy._rootElement).toBeNull() + }) + + it('should respect threshold option', () => { + fixtureEl.innerHTML = [ + '', + '
', + ' ', + '
' + ].join('') + + const scrollSpy = new ScrollSpy('#content', { + target: '#navigation', + threshold: [1] + }) + + expect(scrollSpy._observer.thresholds).toEqual([1]) + }) + + it('should respect threshold option markup', () => { + fixtureEl.innerHTML = [ + '', + '
', + ' ', + '
' + ].join('') + + const scrollSpy = new ScrollSpy('#content', { + target: '#navigation' + }) + + // See https://stackoverflow.com/a/45592926 + const expectToBeCloseToArray = (actual, expected) => { + expect(actual.length).toBe(expected.length) + for (const x of actual) { + const i = actual.indexOf(x) + expect(x).withContext(`[${i}]`).toBeCloseTo(expected[i]) + } + } + + expectToBeCloseToArray(scrollSpy._observer.thresholds, [0, 0.2, 1]) + }) + + it('should not take count to not visible sections', () => { + fixtureEl.innerHTML = [ + '', + '
', + '
test
', + ' ', + ' ', + '
' + ].join('') + + const scrollSpy = new ScrollSpy(fixtureEl.querySelector('#content'), { + target: '#navigation' + }) + + expect(scrollSpy._observableSections.size).toBe(1) + expect(scrollSpy._targetLinks.size).toBe(1) + }) + + it('should not process element without target', () => { + fixtureEl.innerHTML = [ + '', + '
', + '
test
', + '
test2
', + '
' + ].join('') + + const scrollSpy = new ScrollSpy(fixtureEl.querySelector('#content'), { + target: '#navigation' + }) + + expect(scrollSpy._targetLinks).toHaveSize(2) + }) + + it('should only switch "active" class on current target', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '
', + '
', + '
', + '
', + ' ', + '
', + '
', + '
', + '
', + '
Overview
', + '
Detail
', + '
', + '
' + ].join('') + + const scrollSpyEl = fixtureEl.querySelector('#scrollspy-example') + const rootEl = fixtureEl.querySelector('#root') + const scrollSpy = new ScrollSpy(scrollSpyEl, { + target: 'ss-target' + }) + + const spy = spyOn(scrollSpy, '_process').and.callThrough() + + onScrollStop(() => { + expect(rootEl).toHaveClass('active') + expect(spy).toHaveBeenCalled() + resolve() + }, scrollSpyEl) + + scrollTo(scrollSpyEl, 350) + }) + }) + + it('should not process data if `activeTarget` is same as given target', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = [ + '', + '
', + '
div 1
', + '
div 2
', + '
' + ].join('') + + const contentEl = fixtureEl.querySelector('.content') + const scrollSpy = new ScrollSpy(contentEl, { + offset: 0, + target: '.navbar' + }) + + const triggerSpy = spyOn(EventHandler, 'trigger').and.callThrough() + + scrollSpy._activeTarget = fixtureEl.querySelector('#a-1') + testElementIsActiveAfterScroll({ + elementSelector: '#a-1', + targetSelector: '#div-1', + contentEl, + scrollSpy, + cb: reject + }) + + setTimeout(() => { + expect(triggerSpy).not.toHaveBeenCalled() + resolve() + }, 100) + }) + }) + + it('should only switch "active" class on current target specified w element', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '
', + '
', + '
', + '
', + ' ', + '
', + '
', + '
', + '
', + '
Overview
', + '
Detail
', + '
', + '
' + ].join('') + + const scrollSpyEl = fixtureEl.querySelector('#scrollspy-example') + const rootEl = fixtureEl.querySelector('#root') + const scrollSpy = new ScrollSpy(scrollSpyEl, { + target: fixtureEl.querySelector('#ss-target') + }) + + const spy = spyOn(scrollSpy, '_process').and.callThrough() + + onScrollStop(() => { + expect(rootEl).toHaveClass('active') + expect(scrollSpy._activeTarget).toEqual(fixtureEl.querySelector('[href="#detail"]')) + expect(spy).toHaveBeenCalled() + resolve() + }, scrollSpyEl) + + scrollTo(scrollSpyEl, 350) + }) + }) + + it('should add the active class to the correct element', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '
', + '
div 1
', + '
div 2
', + '
' + ].join('') + + const contentEl = fixtureEl.querySelector('.content') + const scrollSpy = new ScrollSpy(contentEl, { + offset: 0, + target: '.navbar' + }) + + testElementIsActiveAfterScroll({ + elementSelector: '#a-1', + targetSelector: '#div-1', + contentEl, + scrollSpy, + cb() { + testElementIsActiveAfterScroll({ + elementSelector: '#a-2', + targetSelector: '#div-2', + contentEl, + scrollSpy, + cb: resolve + }) + } + }) + }) + }) + + it('should add to nav the active class to the correct element (nav markup)', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '
', + '
div 1
', + '
div 2
', + '
' + ].join('') + + const contentEl = fixtureEl.querySelector('.content') + const scrollSpy = new ScrollSpy(contentEl, { + offset: 0, + target: '.navbar' + }) + + testElementIsActiveAfterScroll({ + elementSelector: '#a-1', + targetSelector: '#div-1', + contentEl, + scrollSpy, + cb() { + testElementIsActiveAfterScroll({ + elementSelector: '#a-2', + targetSelector: '#div-2', + contentEl, + scrollSpy, + cb: resolve + }) + } + }) + }) + }) + + it('should add to list-group, the active class to the correct element (list-group markup)', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '
', + '
div 1
', + '
div 2
', + '
' + ].join('') + + const contentEl = fixtureEl.querySelector('.content') + const scrollSpy = new ScrollSpy(contentEl, { + offset: 0, + target: '.navbar' + }) + + testElementIsActiveAfterScroll({ + elementSelector: '#a-1', + targetSelector: '#div-1', + contentEl, + scrollSpy, + cb() { + testElementIsActiveAfterScroll({ + elementSelector: '#a-2', + targetSelector: '#div-2', + contentEl, + scrollSpy, + cb: resolve + }) + } + }) + }) + }) + + it('should clear selection if above the first section', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '', + '
', + '
', + '
text
', + '
text
', + '
text
', + '
', + '
' + ].join('') + + const contentEl = fixtureEl.querySelector('#content') + const scrollSpy = new ScrollSpy(contentEl, { + target: '#navigation', + offset: contentEl.offsetTop + }) + const spy = spyOn(scrollSpy, '_process').and.callThrough() + + onScrollStop(() => { + const active = () => fixtureEl.querySelector('.active') + expect(spy).toHaveBeenCalled() + + expect(fixtureEl.querySelectorAll('.active')).toHaveSize(1) + expect(active().getAttribute('id')).toEqual('two-link') + onScrollStop(() => { + expect(active()).toBeNull() + resolve() + }, contentEl) + scrollTo(contentEl, 0) + }, contentEl) + + scrollTo(contentEl, 200) + }) + }) + + it('should not clear selection if above the first section and first section is at the top', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '', + '
', + '
test
', + '
test
', + '
test
', + '
test
', + '
' + ].join('') + + const negativeHeight = 0 + const startOfSectionTwo = 101 + const contentEl = fixtureEl.querySelector('#content') + // eslint-disable-next-line no-unused-vars + const scrollSpy = new ScrollSpy(contentEl, { + target: '#navigation', + rootMargin: '0px 0px -50%' + }) + + onScrollStop(() => { + const activeId = () => fixtureEl.querySelector('.active').getAttribute('id') + + expect(fixtureEl.querySelectorAll('.active')).toHaveSize(1) + expect(activeId()).toEqual('two-link') + scrollTo(contentEl, negativeHeight) + + onScrollStop(() => { + expect(fixtureEl.querySelectorAll('.active')).toHaveSize(1) + expect(activeId()).toEqual('one-link') + resolve() + }, contentEl) + + scrollTo(contentEl, 0) + }, contentEl) + + scrollTo(contentEl, startOfSectionTwo) + }) + }) + + it('should correctly select navigation element on backward scrolling when each target section height is 100%', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '
', + '
div 1
', + '
div 2
', + '
div 3
', + '
div 4
', + '
div 5
', + '
' + ].join('') + + const contentEl = fixtureEl.querySelector('.content') + const scrollSpy = new ScrollSpy(contentEl, { + offset: 0, + target: '.navbar' + }) + + scrollTo(contentEl, 0) + testElementIsActiveAfterScroll({ + elementSelector: '#li-100-5', + targetSelector: '#div-100-5', + contentEl, + scrollSpy, + cb() { + scrollTo(contentEl, 0) + testElementIsActiveAfterScroll({ + elementSelector: '#li-100-2', + targetSelector: '#div-100-2', + contentEl, + scrollSpy, + cb() { + scrollTo(contentEl, 0) + testElementIsActiveAfterScroll({ + elementSelector: '#li-100-3', + targetSelector: '#div-100-3', + contentEl, + scrollSpy, + cb() { + scrollTo(contentEl, 0) + testElementIsActiveAfterScroll({ + elementSelector: '#li-100-2', + targetSelector: '#div-100-2', + contentEl, + scrollSpy, + cb() { + scrollTo(contentEl, 0) + testElementIsActiveAfterScroll({ + elementSelector: '#li-100-1', + targetSelector: '#div-100-1', + contentEl, + scrollSpy, + cb: resolve + }) + } + }) + } + }) + } + }) + } + }) + }) + }) + }) + + describe('refresh', () => { + it('should disconnect existing observer', () => { + fixtureEl.innerHTML = getDummyFixture() + + const el = fixtureEl.querySelector('.content') + const scrollSpy = new ScrollSpy(el) + + const spy = spyOn(scrollSpy._observer, 'disconnect') + + scrollSpy.refresh() + + expect(spy).toHaveBeenCalled() + }) + }) + + describe('dispose', () => { + it('should dispose a scrollspy', () => { + fixtureEl.innerHTML = getDummyFixture() + + const el = fixtureEl.querySelector('.content') + const scrollSpy = new ScrollSpy(el) + + expect(ScrollSpy.getInstance(el)).not.toBeNull() + + scrollSpy.dispose() + + expect(ScrollSpy.getInstance(el)).toBeNull() + }) + }) + + describe('jQueryInterface', () => { + it('should create a scrollspy', () => { + fixtureEl.innerHTML = getDummyFixture() + + const div = fixtureEl.querySelector('.content') + + jQueryMock.fn.scrollspy = ScrollSpy.jQueryInterface + jQueryMock.elements = [div] + + jQueryMock.fn.scrollspy.call(jQueryMock, { target: '#navBar' }) + + expect(ScrollSpy.getInstance(div)).not.toBeNull() + }) + + it('should create a scrollspy with given config', () => { + fixtureEl.innerHTML = getDummyFixture() + + const div = fixtureEl.querySelector('.content') + + jQueryMock.fn.scrollspy = ScrollSpy.jQueryInterface + jQueryMock.elements = [div] + + jQueryMock.fn.scrollspy.call(jQueryMock, { rootMargin: '100px' }) + const spy = spyOn(ScrollSpy.prototype, 'constructor') + expect(spy).not.toHaveBeenCalledWith(div, { rootMargin: '100px' }) + + const scrollspy = ScrollSpy.getInstance(div) + expect(scrollspy).not.toBeNull() + expect(scrollspy._config.rootMargin).toEqual('100px') + }) + + it('should not re create a scrollspy', () => { + fixtureEl.innerHTML = getDummyFixture() + + const div = fixtureEl.querySelector('.content') + const scrollSpy = new ScrollSpy(div) + + jQueryMock.fn.scrollspy = ScrollSpy.jQueryInterface + jQueryMock.elements = [div] + + jQueryMock.fn.scrollspy.call(jQueryMock) + + expect(ScrollSpy.getInstance(div)).toEqual(scrollSpy) + }) + + it('should call a scrollspy method', () => { + fixtureEl.innerHTML = getDummyFixture() + + const div = fixtureEl.querySelector('.content') + const scrollSpy = new ScrollSpy(div) + + const spy = spyOn(scrollSpy, 'refresh') + + jQueryMock.fn.scrollspy = ScrollSpy.jQueryInterface + jQueryMock.elements = [div] + + jQueryMock.fn.scrollspy.call(jQueryMock, 'refresh') + + expect(ScrollSpy.getInstance(div)).toEqual(scrollSpy) + expect(spy).toHaveBeenCalled() + }) + + it('should throw error on undefined method', () => { + fixtureEl.innerHTML = getDummyFixture() + + const div = fixtureEl.querySelector('.content') + const action = 'undefinedMethod' + + jQueryMock.fn.scrollspy = ScrollSpy.jQueryInterface + jQueryMock.elements = [div] + + expect(() => { + jQueryMock.fn.scrollspy.call(jQueryMock, action) + }).toThrowError(TypeError, `No method named "${action}"`) + }) + + it('should throw error on protected method', () => { + fixtureEl.innerHTML = getDummyFixture() + + const div = fixtureEl.querySelector('.content') + const action = '_getConfig' + + jQueryMock.fn.scrollspy = ScrollSpy.jQueryInterface + jQueryMock.elements = [div] + + expect(() => { + jQueryMock.fn.scrollspy.call(jQueryMock, action) + }).toThrowError(TypeError, `No method named "${action}"`) + }) + + it('should throw error if method "constructor" is being called', () => { + fixtureEl.innerHTML = getDummyFixture() + + const div = fixtureEl.querySelector('.content') + const action = 'constructor' + + jQueryMock.fn.scrollspy = ScrollSpy.jQueryInterface + jQueryMock.elements = [div] + + expect(() => { + jQueryMock.fn.scrollspy.call(jQueryMock, action) + }).toThrowError(TypeError, `No method named "${action}"`) + }) + }) + + describe('getInstance', () => { + it('should return scrollspy instance', () => { + fixtureEl.innerHTML = getDummyFixture() + + const div = fixtureEl.querySelector('.content') + const scrollSpy = new ScrollSpy(div, { target: fixtureEl.querySelector('#navBar') }) + + expect(ScrollSpy.getInstance(div)).toEqual(scrollSpy) + expect(ScrollSpy.getInstance(div)).toBeInstanceOf(ScrollSpy) + }) + + it('should return null if there is no instance', () => { + fixtureEl.innerHTML = getDummyFixture() + + const div = fixtureEl.querySelector('.content') + expect(ScrollSpy.getInstance(div)).toBeNull() + }) + }) + + describe('getOrCreateInstance', () => { + it('should return scrollspy instance', () => { + fixtureEl.innerHTML = getDummyFixture() + + const div = fixtureEl.querySelector('.content') + const scrollspy = new ScrollSpy(div) + + expect(ScrollSpy.getOrCreateInstance(div)).toEqual(scrollspy) + expect(ScrollSpy.getInstance(div)).toEqual(ScrollSpy.getOrCreateInstance(div, {})) + expect(ScrollSpy.getOrCreateInstance(div)).toBeInstanceOf(ScrollSpy) + }) + + it('should return new instance when there is no scrollspy instance', () => { + fixtureEl.innerHTML = getDummyFixture() + + const div = fixtureEl.querySelector('.content') + + expect(ScrollSpy.getInstance(div)).toBeNull() + expect(ScrollSpy.getOrCreateInstance(div)).toBeInstanceOf(ScrollSpy) + }) + + it('should return new instance when there is no scrollspy instance with given configuration', () => { + fixtureEl.innerHTML = getDummyFixture() + + const div = fixtureEl.querySelector('.content') + + expect(ScrollSpy.getInstance(div)).toBeNull() + const scrollspy = ScrollSpy.getOrCreateInstance(div, { + offset: 1 + }) + expect(scrollspy).toBeInstanceOf(ScrollSpy) + + expect(scrollspy._config.offset).toEqual(1) + }) + + it('should return the instance when exists without given configuration', () => { + fixtureEl.innerHTML = getDummyFixture() + + const div = fixtureEl.querySelector('.content') + const scrollspy = new ScrollSpy(div, { + offset: 1 + }) + expect(ScrollSpy.getInstance(div)).toEqual(scrollspy) + + const scrollspy2 = ScrollSpy.getOrCreateInstance(div, { + offset: 2 + }) + expect(scrollspy).toBeInstanceOf(ScrollSpy) + expect(scrollspy2).toEqual(scrollspy) + + expect(scrollspy2._config.offset).toEqual(1) + }) + }) + + describe('event handler', () => { + it('should create scrollspy on window load event', () => { + fixtureEl.innerHTML = [ + '' + + '
' + ].join('') + + const scrollSpyEl = fixtureEl.querySelector('#wrapper') + + window.dispatchEvent(createEvent('load')) + + expect(ScrollSpy.getInstance(scrollSpyEl)).not.toBeNull() + }) + }) + + describe('SmoothScroll', () => { + it('should not enable smoothScroll', () => { + fixtureEl.innerHTML = getDummyFixture() + const offSpy = spyOn(EventHandler, 'off').and.callThrough() + const onSpy = spyOn(EventHandler, 'on').and.callThrough() + + const div = fixtureEl.querySelector('.content') + const target = fixtureEl.querySelector('#navBar') + // eslint-disable-next-line no-new + new ScrollSpy(div, { + offset: 1 + }) + + expect(offSpy).not.toHaveBeenCalledWith(target, 'click.bs.scrollspy') + expect(onSpy).not.toHaveBeenCalledWith(target, 'click.bs.scrollspy') + }) + + it('should enable smoothScroll', () => { + fixtureEl.innerHTML = getDummyFixture() + const offSpy = spyOn(EventHandler, 'off').and.callThrough() + const onSpy = spyOn(EventHandler, 'on').and.callThrough() + + const div = fixtureEl.querySelector('.content') + const target = fixtureEl.querySelector('#navBar') + // eslint-disable-next-line no-new + new ScrollSpy(div, { + offset: 1, + smoothScroll: true + }) + + expect(offSpy).toHaveBeenCalledWith(target, 'click.bs.scrollspy') + expect(onSpy).toHaveBeenCalledWith(target, 'click.bs.scrollspy', '[href]', jasmine.any(Function)) + }) + + it('should not smoothScroll to element if it not handles a scrollspy section', () => { + fixtureEl.innerHTML = [ + '', + '
', + '
div 1
', + '
' + ].join('') + + const div = fixtureEl.querySelector('.content') + // eslint-disable-next-line no-new + new ScrollSpy(div, { + offset: 1, + smoothScroll: true + }) + + const clickSpy = getElementScrollSpy(div) + + fixtureEl.querySelector('#anchor-2').click() + expect(clickSpy).not.toHaveBeenCalled() + }) + + it('should call `scrollTop` if element doesn\'t not support `scrollTo`', () => { + fixtureEl.innerHTML = getDummyFixture() + + const div = fixtureEl.querySelector('.content') + const link = fixtureEl.querySelector('[href="#div-jsm-1"]') + delete div.scrollTo + const clickSpy = getElementScrollSpy(div) + // eslint-disable-next-line no-new + new ScrollSpy(div, { + offset: 1, + smoothScroll: true + }) + + link.click() + expect(clickSpy).toHaveBeenCalled() + }) + + it('should smoothScroll to the proper observable element on anchor click', done => { + fixtureEl.innerHTML = getDummyFixture() + + const div = fixtureEl.querySelector('.content') + const link = fixtureEl.querySelector('[href="#div-jsm-1"]') + const observable = fixtureEl.querySelector('#div-jsm-1') + const clickSpy = getElementScrollSpy(div) + // eslint-disable-next-line no-new + new ScrollSpy(div, { + offset: 1, + smoothScroll: true + }) + + setTimeout(() => { + if (div.scrollTo) { + expect(clickSpy).toHaveBeenCalledWith({ top: observable.offsetTop - div.offsetTop, behavior: 'smooth' }) + } else { + expect(clickSpy).toHaveBeenCalledWith(observable.offsetTop - div.offsetTop) + } + + done() + }, 100) + link.click() + }) + }) +}) diff --git a/js/tests/unit/tab.spec.js b/js/tests/unit/tab.spec.js new file mode 100644 index 0000000..e0c7d86 --- /dev/null +++ b/js/tests/unit/tab.spec.js @@ -0,0 +1,1101 @@ +import Tab from '../../src/tab' +import { clearFixture, createEvent, getFixture, jQueryMock } from '../helpers/fixture' + +describe('Tab', () => { + let fixtureEl + + beforeAll(() => { + fixtureEl = getFixture() + }) + + afterEach(() => { + clearFixture() + }) + + describe('VERSION', () => { + it('should return plugin version', () => { + expect(Tab.VERSION).toEqual(jasmine.any(String)) + }) + }) + + describe('constructor', () => { + it('should take care of element either passed as a CSS selector or DOM element', () => { + fixtureEl.innerHTML = [ + '', + '
    ', + '
  • ', + '
' + ].join('') + + const tabEl = fixtureEl.querySelector('[href="#home"]') + const tabBySelector = new Tab('[href="#home"]') + const tabByElement = new Tab(tabEl) + + expect(tabBySelector._element).toEqual(tabEl) + expect(tabByElement._element).toEqual(tabEl) + }) + + it('Do not Throw exception if not parent', () => { + fixtureEl.innerHTML = [ + fixtureEl.innerHTML = '
' + ].join('') + const navEl = fixtureEl.querySelector('.nav-link') + + expect(() => { + new Tab(navEl) // eslint-disable-line no-new + }).not.toThrowError(TypeError) + }) + }) + + describe('show', () => { + it('should activate element by tab id (using buttons, the preferred semantic way)', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '
    ', + '
  • ', + '
  • ', + '
' + ].join('') + + const profileTriggerEl = fixtureEl.querySelector('#triggerProfile') + const tab = new Tab(profileTriggerEl) + + profileTriggerEl.addEventListener('shown.bs.tab', () => { + expect(fixtureEl.querySelector('#profile')).toHaveClass('active') + expect(profileTriggerEl.getAttribute('aria-selected')).toEqual('true') + resolve() + }) + + tab.show() + }) + }) + + it('should activate element by tab id (using links for tabs - not ideal, but still supported)', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '
    ', + '
  • ', + '
  • ', + '
' + ].join('') + + const profileTriggerEl = fixtureEl.querySelector('#triggerProfile') + const tab = new Tab(profileTriggerEl) + + profileTriggerEl.addEventListener('shown.bs.tab', () => { + expect(fixtureEl.querySelector('#profile')).toHaveClass('active') + expect(profileTriggerEl.getAttribute('aria-selected')).toEqual('true') + resolve() + }) + + tab.show() + }) + }) + + it('should activate element by tab id in ordered list', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '
    ', + '
  1. ', + '
  2. ', + '
' + ].join('') + + const profileTriggerEl = fixtureEl.querySelector('#triggerProfile') + const tab = new Tab(profileTriggerEl) + + profileTriggerEl.addEventListener('shown.bs.tab', () => { + expect(fixtureEl.querySelector('#profile')).toHaveClass('active') + resolve() + }) + + tab.show() + }) + }) + + it('should activate element by tab id in nav list', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '
', + '
', + '
', + '
' + ].join('') + + const profileTriggerEl = fixtureEl.querySelector('#triggerProfile') + const tab = new Tab(profileTriggerEl) + + profileTriggerEl.addEventListener('shown.bs.tab', () => { + expect(fixtureEl.querySelector('#profile')).toHaveClass('active') + resolve() + }) + + tab.show() + }) + }) + + it('should activate element by tab id in list group', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '
', + ' ', + ' ', + '
', + '
', + '
', + '
', + '
' + ].join('') + + const profileTriggerEl = fixtureEl.querySelector('#triggerProfile') + const tab = new Tab(profileTriggerEl) + + profileTriggerEl.addEventListener('shown.bs.tab', () => { + expect(fixtureEl.querySelector('#profile')).toHaveClass('active') + resolve() + }) + + tab.show() + }) + }) + + it('should not fire shown when show is prevented', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = '' + + const navEl = fixtureEl.querySelector('.nav > div') + const tab = new Tab(navEl) + const expectDone = () => { + setTimeout(() => { + expect().nothing() + resolve() + }, 30) + } + + navEl.addEventListener('show.bs.tab', ev => { + ev.preventDefault() + expectDone() + }) + + navEl.addEventListener('shown.bs.tab', () => { + reject(new Error('should not trigger shown event')) + }) + + tab.show() + }) + }) + + it('should not fire shown when tab is already active', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = [ + '', + '
', + '
', + '
', + '
' + ].join('') + + const triggerActive = fixtureEl.querySelector('button.active') + const tab = new Tab(triggerActive) + + triggerActive.addEventListener('shown.bs.tab', () => { + reject(new Error('should not trigger shown event')) + }) + + tab.show() + setTimeout(() => { + expect().nothing() + resolve() + }, 30) + }) + }) + + it('show and shown events should reference correct relatedTarget', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '
', + '
', + '
', + '
' + ].join('') + + const secondTabTrigger = fixtureEl.querySelector('#triggerProfile') + const secondTab = new Tab(secondTabTrigger) + + secondTabTrigger.addEventListener('show.bs.tab', ev => { + expect(ev.relatedTarget.getAttribute('data-bs-target')).toEqual('#home') + }) + + secondTabTrigger.addEventListener('shown.bs.tab', ev => { + expect(ev.relatedTarget.getAttribute('data-bs-target')).toEqual('#home') + expect(secondTabTrigger.getAttribute('aria-selected')).toEqual('true') + expect(fixtureEl.querySelector('button:not(.active)').getAttribute('aria-selected')).toEqual('false') + resolve() + }) + + secondTab.show() + }) + }) + + it('should fire hide and hidden events', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const triggerList = fixtureEl.querySelectorAll('button') + const firstTab = new Tab(triggerList[0]) + const secondTab = new Tab(triggerList[1]) + + let hideCalled = false + triggerList[0].addEventListener('shown.bs.tab', () => { + secondTab.show() + }) + + triggerList[0].addEventListener('hide.bs.tab', ev => { + hideCalled = true + expect(ev.relatedTarget.getAttribute('data-bs-target')).toEqual('#profile') + }) + + triggerList[0].addEventListener('hidden.bs.tab', ev => { + expect(hideCalled).toBeTrue() + expect(ev.relatedTarget.getAttribute('data-bs-target')).toEqual('#profile') + resolve() + }) + + firstTab.show() + }) + }) + + it('should not fire hidden when hide is prevented', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const triggerList = fixtureEl.querySelectorAll('button') + const firstTab = new Tab(triggerList[0]) + const secondTab = new Tab(triggerList[1]) + const expectDone = () => { + setTimeout(() => { + expect().nothing() + resolve() + }, 30) + } + + triggerList[0].addEventListener('shown.bs.tab', () => { + secondTab.show() + }) + + triggerList[0].addEventListener('hide.bs.tab', ev => { + ev.preventDefault() + expectDone() + }) + + triggerList[0].addEventListener('hidden.bs.tab', () => { + reject(new Error('should not trigger hidden')) + }) + + firstTab.show() + }) + }) + + it('should handle removed tabs', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '
', + '
test 1
', + '
test 2
', + '
test 3
', + '
' + ].join('') + + const secondNavEl = fixtureEl.querySelector('#secondNav') + const btnCloseEl = fixtureEl.querySelector('#btnClose') + const secondNavTab = new Tab(secondNavEl) + + secondNavEl.addEventListener('shown.bs.tab', () => { + expect(fixtureEl.querySelectorAll('.nav-tab')).toHaveSize(2) + resolve() + }) + + btnCloseEl.addEventListener('click', () => { + const linkEl = btnCloseEl.parentNode + const liEl = linkEl.parentNode + const tabId = linkEl.getAttribute('href') + const tabIdEl = fixtureEl.querySelector(tabId) + + liEl.remove() + tabIdEl.remove() + secondNavTab.show() + }) + + btnCloseEl.click() + }) + }) + + it('should not focus on opened tab', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '
    ', + '
  • ', + '
  • ', + '
' + ].join('') + + const firstTab = fixtureEl.querySelector('#home') + firstTab.focus() + + const profileTriggerEl = fixtureEl.querySelector('#triggerProfile') + const tab = new Tab(profileTriggerEl) + + profileTriggerEl.addEventListener('shown.bs.tab', () => { + expect(document.activeElement).toBe(firstTab) + expect(document.activeElement).not.toBe(profileTriggerEl) + resolve() + }) + + tab.show() + }) + }) + }) + + describe('dispose', () => { + it('should dispose a tab', () => { + fixtureEl.innerHTML = '' + + const el = fixtureEl.querySelector('.nav > div') + const tab = new Tab(fixtureEl.querySelector('.nav > div')) + + expect(Tab.getInstance(el)).not.toBeNull() + + tab.dispose() + + expect(Tab.getInstance(el)).toBeNull() + }) + }) + + describe('_activate', () => { + it('should not be called if element argument is null', () => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const tabEl = fixtureEl.querySelector('.nav-link') + const tab = new Tab(tabEl) + const spy = jasmine.createSpy('spy') + + const spyQueue = spyOn(tab, '_queueCallback') + tab._activate(null, spy) + expect(spyQueue).not.toHaveBeenCalled() + expect(spy).not.toHaveBeenCalled() + }) + }) + + describe('_setInitialAttributes', () => { + it('should put aria attributes', () => { + fixtureEl.innerHTML = [ + '', + '
', + '
' + ].join('') + + const tabEl = fixtureEl.querySelector('.nav-link') + const parent = fixtureEl.querySelector('.nav') + const children = fixtureEl.querySelectorAll('.nav-link') + const tabPanel = fixtureEl.querySelector('#panel') + const tabPanel2 = fixtureEl.querySelector('#panel2') + + expect(parent.getAttribute('role')).toEqual(null) + expect(tabEl.getAttribute('role')).toEqual(null) + expect(tabPanel.getAttribute('role')).toEqual(null) + const tab = new Tab(tabEl) + tab._setInitialAttributes(parent, children) + + expect(parent.getAttribute('role')).toEqual('tablist') + expect(tabEl.getAttribute('role')).toEqual('tab') + + expect(tabPanel.getAttribute('role')).toEqual('tabpanel') + expect(tabPanel2.getAttribute('role')).toEqual('tabpanel') + expect(tabPanel.hasAttribute('tabindex')).toBeFalse() + expect(tabPanel.hasAttribute('tabindex2')).toBeFalse() + + expect(tabPanel.getAttribute('aria-labelledby')).toEqual('#foo') + expect(tabPanel2.hasAttribute('aria-labelledby')).toBeFalse() + }) + }) + + describe('_keydown', () => { + it('if event is not one of left/right/up/down arrow, ignore it', () => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const tabEl = fixtureEl.querySelector('.nav-link') + const tab = new Tab(tabEl) + + const keydown = createEvent('keydown') + keydown.key = 'Enter' + const spyStop = spyOn(Event.prototype, 'stopPropagation').and.callThrough() + const spyPrevent = spyOn(Event.prototype, 'preventDefault').and.callThrough() + const spyKeydown = spyOn(tab, '_keydown') + const spyGet = spyOn(tab, '_getChildren') + + tabEl.dispatchEvent(keydown) + expect(spyKeydown).toHaveBeenCalled() + expect(spyGet).not.toHaveBeenCalled() + + expect(spyStop).not.toHaveBeenCalled() + expect(spyPrevent).not.toHaveBeenCalled() + }) + + it('if keydown event is right/down arrow, handle it', () => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const tabEl1 = fixtureEl.querySelector('#tab1') + const tabEl2 = fixtureEl.querySelector('#tab2') + const tabEl3 = fixtureEl.querySelector('#tab3') + const tab1 = new Tab(tabEl1) + const tab2 = new Tab(tabEl2) + const tab3 = new Tab(tabEl3) + const spyShow1 = spyOn(tab1, 'show').and.callThrough() + const spyShow2 = spyOn(tab2, 'show').and.callThrough() + const spyShow3 = spyOn(tab3, 'show').and.callThrough() + const spyFocus1 = spyOn(tabEl1, 'focus').and.callThrough() + const spyFocus2 = spyOn(tabEl2, 'focus').and.callThrough() + const spyFocus3 = spyOn(tabEl3, 'focus').and.callThrough() + + const spyStop = spyOn(Event.prototype, 'stopPropagation').and.callThrough() + const spyPrevent = spyOn(Event.prototype, 'preventDefault').and.callThrough() + + let keydown = createEvent('keydown') + keydown.key = 'ArrowRight' + + tabEl1.dispatchEvent(keydown) + expect(spyShow2).toHaveBeenCalled() + expect(spyFocus2).toHaveBeenCalled() + + keydown = createEvent('keydown') + keydown.key = 'ArrowDown' + + tabEl2.dispatchEvent(keydown) + expect(spyShow3).toHaveBeenCalled() + expect(spyFocus3).toHaveBeenCalled() + + tabEl3.dispatchEvent(keydown) + expect(spyShow1).toHaveBeenCalled() + expect(spyFocus1).toHaveBeenCalled() + + expect(spyStop).toHaveBeenCalledTimes(3) + expect(spyPrevent).toHaveBeenCalledTimes(3) + }) + + it('if keydown event is left arrow, handle it', () => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const tabEl1 = fixtureEl.querySelector('#tab1') + const tabEl2 = fixtureEl.querySelector('#tab2') + const tab1 = new Tab(tabEl1) + const tab2 = new Tab(tabEl2) + const spyShow1 = spyOn(tab1, 'show').and.callThrough() + const spyShow2 = spyOn(tab2, 'show').and.callThrough() + const spyFocus1 = spyOn(tabEl1, 'focus').and.callThrough() + const spyFocus2 = spyOn(tabEl2, 'focus').and.callThrough() + + const spyStop = spyOn(Event.prototype, 'stopPropagation').and.callThrough() + const spyPrevent = spyOn(Event.prototype, 'preventDefault').and.callThrough() + + let keydown = createEvent('keydown') + keydown.key = 'ArrowLeft' + + tabEl2.dispatchEvent(keydown) + expect(spyShow1).toHaveBeenCalled() + expect(spyFocus1).toHaveBeenCalled() + + keydown = createEvent('keydown') + keydown.key = 'ArrowUp' + + tabEl1.dispatchEvent(keydown) + expect(spyShow2).toHaveBeenCalled() + expect(spyFocus2).toHaveBeenCalled() + + expect(spyStop).toHaveBeenCalledTimes(2) + expect(spyPrevent).toHaveBeenCalledTimes(2) + }) + + it('if keydown event is right arrow and next element is disabled', () => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const tabEl = fixtureEl.querySelector('#tab1') + const tabEl2 = fixtureEl.querySelector('#tab2') + const tabEl3 = fixtureEl.querySelector('#tab3') + const tabEl4 = fixtureEl.querySelector('#tab4') + const tab = new Tab(tabEl) + const tab2 = new Tab(tabEl2) + const tab3 = new Tab(tabEl3) + const tab4 = new Tab(tabEl4) + const spy1 = spyOn(tab, 'show').and.callThrough() + const spy2 = spyOn(tab2, 'show').and.callThrough() + const spy3 = spyOn(tab3, 'show').and.callThrough() + const spy4 = spyOn(tab4, 'show').and.callThrough() + const spyFocus1 = spyOn(tabEl, 'focus').and.callThrough() + const spyFocus2 = spyOn(tabEl2, 'focus').and.callThrough() + const spyFocus3 = spyOn(tabEl3, 'focus').and.callThrough() + const spyFocus4 = spyOn(tabEl4, 'focus').and.callThrough() + + const keydown = createEvent('keydown') + keydown.key = 'ArrowRight' + + tabEl.dispatchEvent(keydown) + expect(spy1).not.toHaveBeenCalled() + expect(spy2).not.toHaveBeenCalled() + expect(spy3).not.toHaveBeenCalled() + expect(spy4).toHaveBeenCalledTimes(1) + expect(spyFocus1).not.toHaveBeenCalled() + expect(spyFocus2).not.toHaveBeenCalled() + expect(spyFocus3).not.toHaveBeenCalled() + expect(spyFocus4).toHaveBeenCalledTimes(1) + }) + + it('if keydown event is left arrow and next element is disabled', () => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const tabEl = fixtureEl.querySelector('#tab1') + const tabEl2 = fixtureEl.querySelector('#tab2') + const tabEl3 = fixtureEl.querySelector('#tab3') + const tabEl4 = fixtureEl.querySelector('#tab4') + const tab = new Tab(tabEl) + const tab2 = new Tab(tabEl2) + const tab3 = new Tab(tabEl3) + const tab4 = new Tab(tabEl4) + const spy1 = spyOn(tab, 'show').and.callThrough() + const spy2 = spyOn(tab2, 'show').and.callThrough() + const spy3 = spyOn(tab3, 'show').and.callThrough() + const spy4 = spyOn(tab4, 'show').and.callThrough() + const spyFocus1 = spyOn(tabEl, 'focus').and.callThrough() + const spyFocus2 = spyOn(tabEl2, 'focus').and.callThrough() + const spyFocus3 = spyOn(tabEl3, 'focus').and.callThrough() + const spyFocus4 = spyOn(tabEl4, 'focus').and.callThrough() + + const keydown = createEvent('keydown') + keydown.key = 'ArrowLeft' + + tabEl4.dispatchEvent(keydown) + expect(spy4).not.toHaveBeenCalled() + expect(spy3).not.toHaveBeenCalled() + expect(spy2).not.toHaveBeenCalled() + expect(spy1).toHaveBeenCalledTimes(1) + expect(spyFocus4).not.toHaveBeenCalled() + expect(spyFocus3).not.toHaveBeenCalled() + expect(spyFocus2).not.toHaveBeenCalled() + expect(spyFocus1).toHaveBeenCalledTimes(1) + }) + }) + + describe('jQueryInterface', () => { + it('should create a tab', () => { + fixtureEl.innerHTML = '' + + const div = fixtureEl.querySelector('.nav > div') + + jQueryMock.fn.tab = Tab.jQueryInterface + jQueryMock.elements = [div] + + jQueryMock.fn.tab.call(jQueryMock) + + expect(Tab.getInstance(div)).not.toBeNull() + }) + + it('should not re create a tab', () => { + fixtureEl.innerHTML = '' + + const div = fixtureEl.querySelector('.nav > div') + const tab = new Tab(div) + + jQueryMock.fn.tab = Tab.jQueryInterface + jQueryMock.elements = [div] + + jQueryMock.fn.tab.call(jQueryMock) + + expect(Tab.getInstance(div)).toEqual(tab) + }) + + it('should call a tab method', () => { + fixtureEl.innerHTML = '' + + const div = fixtureEl.querySelector('.nav > div') + const tab = new Tab(div) + + const spy = spyOn(tab, 'show') + + jQueryMock.fn.tab = Tab.jQueryInterface + jQueryMock.elements = [div] + + jQueryMock.fn.tab.call(jQueryMock, 'show') + + expect(Tab.getInstance(div)).toEqual(tab) + expect(spy).toHaveBeenCalled() + }) + + it('should throw error on undefined method', () => { + fixtureEl.innerHTML = '' + + const div = fixtureEl.querySelector('.nav > div') + const action = 'undefinedMethod' + + jQueryMock.fn.tab = Tab.jQueryInterface + jQueryMock.elements = [div] + + expect(() => { + jQueryMock.fn.tab.call(jQueryMock, action) + }).toThrowError(TypeError, `No method named "${action}"`) + }) + }) + + describe('getInstance', () => { + it('should return null if there is no instance', () => { + expect(Tab.getInstance(fixtureEl)).toBeNull() + }) + + it('should return this instance', () => { + fixtureEl.innerHTML = '' + + const divEl = fixtureEl.querySelector('.nav > div') + const tab = new Tab(divEl) + + expect(Tab.getInstance(divEl)).toEqual(tab) + expect(Tab.getInstance(divEl)).toBeInstanceOf(Tab) + }) + }) + + describe('getOrCreateInstance', () => { + it('should return tab instance', () => { + fixtureEl.innerHTML = '' + + const div = fixtureEl.querySelector('div') + const tab = new Tab(div) + + expect(Tab.getOrCreateInstance(div)).toEqual(tab) + expect(Tab.getInstance(div)).toEqual(Tab.getOrCreateInstance(div, {})) + expect(Tab.getOrCreateInstance(div)).toBeInstanceOf(Tab) + }) + + it('should return new instance when there is no tab instance', () => { + fixtureEl.innerHTML = '' + + const div = fixtureEl.querySelector('div') + + expect(Tab.getInstance(div)).toBeNull() + expect(Tab.getOrCreateInstance(div)).toBeInstanceOf(Tab) + }) + }) + + describe('data-api', () => { + it('should create dynamically a tab', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '
', + '
', + '
', + '
' + ].join('') + + const secondTabTrigger = fixtureEl.querySelector('#triggerProfile') + + secondTabTrigger.addEventListener('shown.bs.tab', () => { + expect(secondTabTrigger).toHaveClass('active') + expect(fixtureEl.querySelector('#profile')).toHaveClass('active') + resolve() + }) + + secondTabTrigger.click() + }) + }) + + it('selected tab should deactivate previous selected link in dropdown', () => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const firstLiLinkEl = fixtureEl.querySelector('li:first-child a') + + firstLiLinkEl.click() + expect(firstLiLinkEl).toHaveClass('active') + expect(fixtureEl.querySelector('li:last-child a')).not.toHaveClass('active') + expect(fixtureEl.querySelector('li:last-child .dropdown-menu a:first-child')).not.toHaveClass('active') + }) + + it('selecting a dropdown tab does not activate another', () => { + const nav1 = [ + '' + ].join('') + const nav2 = [ + '' + ].join('') + + fixtureEl.innerHTML = nav1 + nav2 + + const firstDropItem = fixtureEl.querySelector('#nav1 .dropdown-item') + + firstDropItem.click() + expect(firstDropItem).toHaveClass('active') + expect(fixtureEl.querySelector('#nav1 .dropdown-toggle')).toHaveClass('active') + expect(fixtureEl.querySelector('#nav2 .dropdown-toggle')).not.toHaveClass('active') + expect(fixtureEl.querySelector('#nav2 .dropdown-item')).not.toHaveClass('active') + }) + + it('should support li > .dropdown-item', () => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const dropItems = fixtureEl.querySelectorAll('.dropdown-item') + + dropItems[1].click() + expect(dropItems[0]).not.toHaveClass('active') + expect(dropItems[1]).toHaveClass('active') + expect(fixtureEl.querySelector('.nav-link')).not.toHaveClass('active') + }) + + it('should handle nested tabs', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '
', + '
', + ' ', + '
', + '
Nested Tab1 Content
', + '
Nested Tab2 Content
', + '
', + '
', + '
Tab2 Content
', + '
Tab3 Content
', + '
' + ].join('') + + const tab1El = fixtureEl.querySelector('#tab1') + const tabNested2El = fixtureEl.querySelector('#tabNested2') + const xTab1El = fixtureEl.querySelector('#x-tab1') + + tabNested2El.addEventListener('shown.bs.tab', () => { + expect(xTab1El).toHaveClass('active') + resolve() + }) + + tab1El.addEventListener('shown.bs.tab', () => { + expect(xTab1El).toHaveClass('active') + tabNested2El.click() + }) + + tab1El.click() + }) + }) + + it('should not remove fade class if no active pane is present', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '
', + '
', + '
', + '
' + ].join('') + + const triggerTabProfileEl = fixtureEl.querySelector('#tab-profile') + const triggerTabHomeEl = fixtureEl.querySelector('#tab-home') + const tabProfileEl = fixtureEl.querySelector('#profile') + const tabHomeEl = fixtureEl.querySelector('#home') + + triggerTabHomeEl.addEventListener('shown.bs.tab', () => { + setTimeout(() => { + expect(tabProfileEl).toHaveClass('fade') + expect(tabProfileEl).not.toHaveClass('show') + + expect(tabHomeEl).toHaveClass('fade') + expect(tabHomeEl).toHaveClass('show') + + resolve() + }, 10) + }) + + triggerTabProfileEl.addEventListener('shown.bs.tab', () => { + setTimeout(() => { + expect(tabProfileEl).toHaveClass('fade') + expect(tabProfileEl).toHaveClass('show') + triggerTabHomeEl.click() + }, 10) + }) + + triggerTabProfileEl.click() + }) + }) + + it('should add `show` class to tab panes if there is no `.fade` class', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '
', + '
test 1
', + '
test 2
', + '
' + ].join('') + + const secondNavEl = fixtureEl.querySelector('#secondNav') + + secondNavEl.addEventListener('shown.bs.tab', () => { + expect(fixtureEl.querySelectorAll('.tab-content .show')).toHaveSize(1) + resolve() + }) + + secondNavEl.click() + }) + }) + + it('should add show class to tab panes if there is a `.fade` class', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '
', + '
test 1
', + '
test 2
', + '
' + ].join('') + + const secondNavEl = fixtureEl.querySelector('#secondNav') + + secondNavEl.addEventListener('shown.bs.tab', () => { + setTimeout(() => { + expect(fixtureEl.querySelectorAll('.show')).toHaveSize(1) + resolve() + }, 10) + }) + + secondNavEl.click() + }) + }) + + it('should prevent default when the trigger is or ', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '' + ].join('') + + const tabEl = fixtureEl.querySelector('[href="#test2"]') + const spy = spyOn(Event.prototype, 'preventDefault').and.callThrough() + + tabEl.addEventListener('shown.bs.tab', () => { + expect(tabEl).toHaveClass('active') + expect(spy).toHaveBeenCalled() + resolve() + }) + + tabEl.click() + }) + }) + + it('should not fire shown when tab has disabled attribute', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = [ + '', + '
', + '
', + '
', + '
' + ].join('') + + const triggerDisabled = fixtureEl.querySelector('button[disabled]') + triggerDisabled.addEventListener('shown.bs.tab', () => { + reject(new Error('should not trigger shown event')) + }) + + triggerDisabled.click() + setTimeout(() => { + expect().nothing() + resolve() + }, 30) + }) + }) + + it('should not fire shown when tab has disabled class', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = [ + '', + '
', + '
', + '
', + '
' + ].join('') + + const triggerDisabled = fixtureEl.querySelector('a.disabled') + + triggerDisabled.addEventListener('shown.bs.tab', () => { + reject(new Error('should not trigger shown event')) + }) + + triggerDisabled.click() + setTimeout(() => { + expect().nothing() + resolve() + }, 30) + }) + }) + }) +}) diff --git a/js/tests/unit/toast.spec.js b/js/tests/unit/toast.spec.js new file mode 100644 index 0000000..42d2515 --- /dev/null +++ b/js/tests/unit/toast.spec.js @@ -0,0 +1,670 @@ +import Toast from '../../src/toast' +import { clearFixture, createEvent, getFixture, jQueryMock } from '../helpers/fixture' + +describe('Toast', () => { + let fixtureEl + + beforeAll(() => { + fixtureEl = getFixture() + }) + + afterEach(() => { + clearFixture() + }) + + describe('VERSION', () => { + it('should return plugin version', () => { + expect(Toast.VERSION).toEqual(jasmine.any(String)) + }) + }) + + describe('DATA_KEY', () => { + it('should return plugin data key', () => { + expect(Toast.DATA_KEY).toEqual('bs.toast') + }) + }) + + describe('constructor', () => { + it('should take care of element either passed as a CSS selector or DOM element', () => { + fixtureEl.innerHTML = '
' + + const toastEl = fixtureEl.querySelector('.toast') + const toastBySelector = new Toast('.toast') + const toastByElement = new Toast(toastEl) + + expect(toastBySelector._element).toEqual(toastEl) + expect(toastByElement._element).toEqual(toastEl) + }) + + it('should allow to config in js', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '
', + '
', + ' a simple toast', + '
', + '
' + ].join('') + + const toastEl = fixtureEl.querySelector('div') + const toast = new Toast(toastEl, { + delay: 1 + }) + + toastEl.addEventListener('shown.bs.toast', () => { + expect(toastEl).toHaveClass('show') + resolve() + }) + + toast.show() + }) + }) + + it('should close toast when close element with data-bs-dismiss attribute is set', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '
', + ' ', + '
' + ].join('') + + const toastEl = fixtureEl.querySelector('div') + const toast = new Toast(toastEl) + + toastEl.addEventListener('shown.bs.toast', () => { + expect(toastEl).toHaveClass('show') + + const button = toastEl.querySelector('.btn-close') + + button.click() + }) + + toastEl.addEventListener('hidden.bs.toast', () => { + expect(toastEl).not.toHaveClass('show') + resolve() + }) + + toast.show() + }) + }) + }) + + describe('Default', () => { + it('should expose default setting to allow to override them', () => { + const defaultDelay = 1000 + + Toast.Default.delay = defaultDelay + + fixtureEl.innerHTML = [ + '
', + ' ', + '
' + ].join('') + + const toastEl = fixtureEl.querySelector('div') + const toast = new Toast(toastEl) + + expect(toast._config.delay).toEqual(defaultDelay) + }) + }) + + describe('DefaultType', () => { + it('should expose default setting types for read', () => { + expect(Toast.DefaultType).toEqual(jasmine.any(Object)) + }) + }) + + describe('show', () => { + it('should auto hide', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '
', + '
', + ' a simple toast', + '
', + '
' + ].join('') + + const toastEl = fixtureEl.querySelector('.toast') + const toast = new Toast(toastEl) + + toastEl.addEventListener('hidden.bs.toast', () => { + expect(toastEl).not.toHaveClass('show') + resolve() + }) + + toast.show() + }) + }) + + it('should not add fade class', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '
', + '
', + ' a simple toast', + '
', + '
' + ].join('') + + const toastEl = fixtureEl.querySelector('.toast') + const toast = new Toast(toastEl) + + toastEl.addEventListener('shown.bs.toast', () => { + expect(toastEl).not.toHaveClass('fade') + resolve() + }) + + toast.show() + }) + }) + + it('should not trigger shown if show is prevented', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = [ + '
', + '
', + ' a simple toast', + '
', + '
' + ].join('') + + const toastEl = fixtureEl.querySelector('.toast') + const toast = new Toast(toastEl) + + const assertDone = () => { + setTimeout(() => { + expect(toastEl).not.toHaveClass('show') + resolve() + }, 20) + } + + toastEl.addEventListener('show.bs.toast', event => { + event.preventDefault() + assertDone() + }) + + toastEl.addEventListener('shown.bs.toast', () => { + reject(new Error('shown event should not be triggered if show is prevented')) + }) + + toast.show() + }) + }) + + it('should clear timeout if toast is shown again before it is hidden', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '
', + '
', + ' a simple toast', + '
', + '
' + ].join('') + + const toastEl = fixtureEl.querySelector('.toast') + const toast = new Toast(toastEl) + + setTimeout(() => { + toast._config.autohide = false + toastEl.addEventListener('shown.bs.toast', () => { + expect(spy).toHaveBeenCalled() + expect(toast._timeout).toBeNull() + resolve() + }) + toast.show() + }, toast._config.delay / 2) + + const spy = spyOn(toast, '_clearTimeout').and.callThrough() + + toast.show() + }) + }) + + it('should clear timeout if toast is interacted with mouse', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '
', + '
', + ' a simple toast', + '
', + '
' + ].join('') + + const toastEl = fixtureEl.querySelector('.toast') + const toast = new Toast(toastEl) + const spy = spyOn(toast, '_clearTimeout').and.callThrough() + + setTimeout(() => { + spy.calls.reset() + + toastEl.addEventListener('mouseover', () => { + expect(toast._clearTimeout).toHaveBeenCalledTimes(1) + expect(toast._timeout).toBeNull() + resolve() + }) + + const mouseOverEvent = createEvent('mouseover') + toastEl.dispatchEvent(mouseOverEvent) + }, toast._config.delay / 2) + + toast.show() + }) + }) + + it('should clear timeout if toast is interacted with keyboard', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '
', + '
', + ' a simple toast', + ' ', + '
', + '
' + ].join('') + + const toastEl = fixtureEl.querySelector('.toast') + const toast = new Toast(toastEl) + const spy = spyOn(toast, '_clearTimeout').and.callThrough() + + setTimeout(() => { + spy.calls.reset() + + toastEl.addEventListener('focusin', () => { + expect(toast._clearTimeout).toHaveBeenCalledTimes(1) + expect(toast._timeout).toBeNull() + resolve() + }) + + const insideFocusable = toastEl.querySelector('button') + insideFocusable.focus() + }, toast._config.delay / 2) + + toast.show() + }) + }) + + it('should still auto hide after being interacted with mouse and keyboard', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '
', + '
', + ' a simple toast', + ' ', + '
', + '
' + ].join('') + + const toastEl = fixtureEl.querySelector('.toast') + const toast = new Toast(toastEl) + + setTimeout(() => { + toastEl.addEventListener('mouseover', () => { + const insideFocusable = toastEl.querySelector('button') + insideFocusable.focus() + }) + + toastEl.addEventListener('focusin', () => { + const mouseOutEvent = createEvent('mouseout') + toastEl.dispatchEvent(mouseOutEvent) + }) + + toastEl.addEventListener('mouseout', () => { + const outsideFocusable = document.getElementById('outside-focusable') + outsideFocusable.focus() + }) + + toastEl.addEventListener('focusout', () => { + expect(toast._timeout).not.toBeNull() + resolve() + }) + + const mouseOverEvent = createEvent('mouseover') + toastEl.dispatchEvent(mouseOverEvent) + }, toast._config.delay / 2) + + toast.show() + }) + }) + + it('should not auto hide if focus leaves but mouse pointer remains inside', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '
', + '
', + ' a simple toast', + ' ', + '
', + '
' + ].join('') + + const toastEl = fixtureEl.querySelector('.toast') + const toast = new Toast(toastEl) + + setTimeout(() => { + toastEl.addEventListener('mouseover', () => { + const insideFocusable = toastEl.querySelector('button') + insideFocusable.focus() + }) + + toastEl.addEventListener('focusin', () => { + const outsideFocusable = document.getElementById('outside-focusable') + outsideFocusable.focus() + }) + + toastEl.addEventListener('focusout', () => { + expect(toast._timeout).toBeNull() + resolve() + }) + + const mouseOverEvent = createEvent('mouseover') + toastEl.dispatchEvent(mouseOverEvent) + }, toast._config.delay / 2) + + toast.show() + }) + }) + + it('should not auto hide if mouse pointer leaves but focus remains inside', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '
', + '
', + ' a simple toast', + ' ', + '
', + '
' + ].join('') + + const toastEl = fixtureEl.querySelector('.toast') + const toast = new Toast(toastEl) + + setTimeout(() => { + toastEl.addEventListener('mouseover', () => { + const insideFocusable = toastEl.querySelector('button') + insideFocusable.focus() + }) + + toastEl.addEventListener('focusin', () => { + const mouseOutEvent = createEvent('mouseout') + toastEl.dispatchEvent(mouseOutEvent) + }) + + toastEl.addEventListener('mouseout', () => { + expect(toast._timeout).toBeNull() + resolve() + }) + + const mouseOverEvent = createEvent('mouseover') + toastEl.dispatchEvent(mouseOverEvent) + }, toast._config.delay / 2) + + toast.show() + }) + }) + }) + + describe('hide', () => { + it('should allow to hide toast manually', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '
', + '
', + ' a simple toast', + '
', + '
' + ].join('') + + const toastEl = fixtureEl.querySelector('.toast') + const toast = new Toast(toastEl) + + toastEl.addEventListener('shown.bs.toast', () => { + toast.hide() + }) + + toastEl.addEventListener('hidden.bs.toast', () => { + expect(toastEl).not.toHaveClass('show') + resolve() + }) + + toast.show() + }) + }) + + it('should do nothing when we call hide on a non shown toast', () => { + fixtureEl.innerHTML = '
' + + const toastEl = fixtureEl.querySelector('div') + const toast = new Toast(toastEl) + + const spy = spyOn(toastEl.classList, 'contains') + + toast.hide() + + expect(spy).toHaveBeenCalled() + }) + + it('should not trigger hidden if hide is prevented', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = [ + '
', + '
', + ' a simple toast', + '
', + '
' + ].join('') + + const toastEl = fixtureEl.querySelector('.toast') + const toast = new Toast(toastEl) + + const assertDone = () => { + setTimeout(() => { + expect(toastEl).toHaveClass('show') + resolve() + }, 20) + } + + toastEl.addEventListener('shown.bs.toast', () => { + toast.hide() + }) + + toastEl.addEventListener('hide.bs.toast', event => { + event.preventDefault() + assertDone() + }) + + toastEl.addEventListener('hidden.bs.toast', () => { + reject(new Error('hidden event should not be triggered if hide is prevented')) + }) + + toast.show() + }) + }) + }) + + describe('dispose', () => { + it('should allow to destroy toast', () => { + fixtureEl.innerHTML = '
' + + const toastEl = fixtureEl.querySelector('div') + + const toast = new Toast(toastEl) + + expect(Toast.getInstance(toastEl)).not.toBeNull() + + toast.dispose() + + expect(Toast.getInstance(toastEl)).toBeNull() + }) + + it('should allow to destroy toast and hide it before that', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '
', + '
', + ' a simple toast', + '
', + '
' + ].join('') + + const toastEl = fixtureEl.querySelector('div') + const toast = new Toast(toastEl) + const expected = () => { + expect(toastEl).toHaveClass('show') + expect(Toast.getInstance(toastEl)).not.toBeNull() + + toast.dispose() + + expect(Toast.getInstance(toastEl)).toBeNull() + expect(toastEl).not.toHaveClass('show') + + resolve() + } + + toastEl.addEventListener('shown.bs.toast', () => { + setTimeout(expected, 1) + }) + + toast.show() + }) + }) + }) + + describe('jQueryInterface', () => { + it('should create a toast', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + jQueryMock.fn.toast = Toast.jQueryInterface + jQueryMock.elements = [div] + + jQueryMock.fn.toast.call(jQueryMock) + + expect(Toast.getInstance(div)).not.toBeNull() + }) + + it('should not re create a toast', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const toast = new Toast(div) + + jQueryMock.fn.toast = Toast.jQueryInterface + jQueryMock.elements = [div] + + jQueryMock.fn.toast.call(jQueryMock) + + expect(Toast.getInstance(div)).toEqual(toast) + }) + + it('should call a toast method', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const toast = new Toast(div) + + const spy = spyOn(toast, 'show') + + jQueryMock.fn.toast = Toast.jQueryInterface + jQueryMock.elements = [div] + + jQueryMock.fn.toast.call(jQueryMock, 'show') + + expect(Toast.getInstance(div)).toEqual(toast) + expect(spy).toHaveBeenCalled() + }) + + it('should throw error on undefined method', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const action = 'undefinedMethod' + + jQueryMock.fn.toast = Toast.jQueryInterface + jQueryMock.elements = [div] + + expect(() => { + jQueryMock.fn.toast.call(jQueryMock, action) + }).toThrowError(TypeError, `No method named "${action}"`) + }) + }) + + describe('getInstance', () => { + it('should return a toast instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const toast = new Toast(div) + + expect(Toast.getInstance(div)).toEqual(toast) + expect(Toast.getInstance(div)).toBeInstanceOf(Toast) + }) + + it('should return null when there is no toast instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(Toast.getInstance(div)).toBeNull() + }) + }) + + describe('getOrCreateInstance', () => { + it('should return toast instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const toast = new Toast(div) + + expect(Toast.getOrCreateInstance(div)).toEqual(toast) + expect(Toast.getInstance(div)).toEqual(Toast.getOrCreateInstance(div, {})) + expect(Toast.getOrCreateInstance(div)).toBeInstanceOf(Toast) + }) + + it('should return new instance when there is no toast instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(Toast.getInstance(div)).toBeNull() + expect(Toast.getOrCreateInstance(div)).toBeInstanceOf(Toast) + }) + + it('should return new instance when there is no toast instance with given configuration', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(Toast.getInstance(div)).toBeNull() + const toast = Toast.getOrCreateInstance(div, { + delay: 1 + }) + expect(toast).toBeInstanceOf(Toast) + + expect(toast._config.delay).toEqual(1) + }) + + it('should return the instance when exists without given configuration', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const toast = new Toast(div, { + delay: 1 + }) + expect(Toast.getInstance(div)).toEqual(toast) + + const toast2 = Toast.getOrCreateInstance(div, { + delay: 2 + }) + expect(toast).toBeInstanceOf(Toast) + expect(toast2).toEqual(toast) + + expect(toast2._config.delay).toEqual(1) + }) + }) +}) diff --git a/js/tests/unit/tooltip.spec.js b/js/tests/unit/tooltip.spec.js new file mode 100644 index 0000000..4330571 --- /dev/null +++ b/js/tests/unit/tooltip.spec.js @@ -0,0 +1,1551 @@ +import Tooltip from '../../src/tooltip' +import EventHandler from '../../src/dom/event-handler' +import { noop } from '../../src/util/index' +import { clearFixture, createEvent, getFixture, jQueryMock } from '../helpers/fixture' + +describe('Tooltip', () => { + let fixtureEl + + beforeAll(() => { + fixtureEl = getFixture() + }) + + afterEach(() => { + clearFixture() + + for (const tooltipEl of document.querySelectorAll('.tooltip')) { + tooltipEl.remove() + } + }) + + describe('VERSION', () => { + it('should return plugin version', () => { + expect(Tooltip.VERSION).toEqual(jasmine.any(String)) + }) + }) + + describe('Default', () => { + it('should return plugin default config', () => { + expect(Tooltip.Default).toEqual(jasmine.any(Object)) + }) + }) + + describe('NAME', () => { + it('should return plugin name', () => { + expect(Tooltip.NAME).toEqual(jasmine.any(String)) + }) + }) + + describe('DATA_KEY', () => { + it('should return plugin data key', () => { + expect(Tooltip.DATA_KEY).toEqual('bs.tooltip') + }) + }) + + describe('EVENT_KEY', () => { + it('should return plugin event key', () => { + expect(Tooltip.EVENT_KEY).toEqual('.bs.tooltip') + }) + }) + + describe('DefaultType', () => { + it('should return plugin default type', () => { + expect(Tooltip.DefaultType).toEqual(jasmine.any(Object)) + }) + }) + + describe('constructor', () => { + it('should take care of element either passed as a CSS selector or DOM element', () => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('#tooltipEl') + const tooltipBySelector = new Tooltip('#tooltipEl') + const tooltipByElement = new Tooltip(tooltipEl) + + expect(tooltipBySelector._element).toEqual(tooltipEl) + expect(tooltipByElement._element).toEqual(tooltipEl) + }) + + it('should not take care of disallowed data attributes', () => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + expect(tooltip._config.sanitize).toBeTrue() + }) + + it('should convert title and content to string if numbers', () => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl, { + title: 1, + content: 7 + }) + + expect(tooltip._config.title).toEqual('1') + expect(tooltip._config.content).toEqual('7') + }) + + it('should enable selector delegation', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + + const containerEl = fixtureEl.querySelector('div') + const tooltipContainer = new Tooltip(containerEl, { + selector: 'a[rel="tooltip"]', + trigger: 'click' + }) + + containerEl.innerHTML = '
' + + const tooltipInContainerEl = containerEl.querySelector('a') + + tooltipInContainerEl.addEventListener('shown.bs.tooltip', () => { + expect(document.querySelector('.tooltip')).not.toBeNull() + tooltipContainer.dispose() + resolve() + }) + + tooltipInContainerEl.click() + }) + }) + + it('should create offset modifier when offset is passed as a function', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const getOffset = jasmine.createSpy('getOffset').and.returnValue([10, 20]) + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl, { + offset: getOffset, + popperConfig: { + onFirstUpdate(state) { + expect(getOffset).toHaveBeenCalledWith({ + popper: state.rects.popper, + reference: state.rects.reference, + placement: state.placement + }, tooltipEl) + resolve() + } + } + }) + + const offset = tooltip._getOffset() + + expect(offset).toEqual(jasmine.any(Function)) + + tooltip.show() + }) + }) + + it('should create offset modifier when offset option is passed in data attribute', () => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + expect(tooltip._getOffset()).toEqual([10, 20]) + }) + + it('should allow to pass config to Popper with `popperConfig`', () => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl, { + popperConfig: { + placement: 'left' + } + }) + + const popperConfig = tooltip._getPopperConfig('top') + + expect(popperConfig.placement).toEqual('left') + }) + + it('should allow to pass config to Popper with `popperConfig` as a function', () => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const getPopperConfig = jasmine.createSpy('getPopperConfig').and.returnValue({ placement: 'left' }) + const tooltip = new Tooltip(tooltipEl, { + popperConfig: getPopperConfig + }) + + const popperConfig = tooltip._getPopperConfig('top') + + expect(getPopperConfig).toHaveBeenCalled() + expect(popperConfig.placement).toEqual('left') + }) + + it('should use original title, if not "data-bs-title" is given', () => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + expect(tooltip._getTitle()).toEqual('Another tooltip') + }) + }) + + describe('enable', () => { + it('should enable a tooltip', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + tooltip.enable() + + tooltipEl.addEventListener('shown.bs.tooltip', () => { + expect(document.querySelector('.tooltip')).not.toBeNull() + resolve() + }) + + tooltip.show() + }) + }) + }) + + describe('disable', () => { + it('should disable tooltip', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + tooltip.disable() + + tooltipEl.addEventListener('show.bs.tooltip', () => { + reject(new Error('should not show a disabled tooltip')) + }) + + tooltip.show() + + setTimeout(() => { + expect().nothing() + resolve() + }, 10) + }) + }) + }) + + describe('toggleEnabled', () => { + it('should toggle enabled', () => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + expect(tooltip._isEnabled).toBeTrue() + + tooltip.toggleEnabled() + + expect(tooltip._isEnabled).toBeFalse() + }) + }) + + describe('toggle', () => { + it('should do nothing if disabled', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + tooltip.disable() + + tooltipEl.addEventListener('show.bs.tooltip', () => { + reject(new Error('should not show a disabled tooltip')) + }) + + tooltip.toggle() + + setTimeout(() => { + expect().nothing() + resolve() + }, 10) + }) + }) + + it('should show a tooltip', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + tooltipEl.addEventListener('shown.bs.tooltip', () => { + expect(document.querySelector('.tooltip')).not.toBeNull() + resolve() + }) + + tooltip.toggle() + }) + }) + + it('should call toggle and show the tooltip when trigger is "click"', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl, { + trigger: 'click' + }) + + const spy = spyOn(tooltip, 'toggle').and.callThrough() + + tooltipEl.addEventListener('shown.bs.tooltip', () => { + expect(spy).toHaveBeenCalled() + resolve() + }) + + tooltipEl.click() + }) + }) + + it('should hide a tooltip', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + tooltipEl.addEventListener('shown.bs.tooltip', () => { + tooltip.toggle() + }) + + tooltipEl.addEventListener('hidden.bs.tooltip', () => { + expect(document.querySelector('.tooltip')).toBeNull() + resolve() + }) + + tooltip.toggle() + }) + }) + + it('should call toggle and hide the tooltip when trigger is "click"', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl, { + trigger: 'click' + }) + + const spy = spyOn(tooltip, 'toggle').and.callThrough() + + tooltipEl.addEventListener('shown.bs.tooltip', () => { + tooltipEl.click() + }) + + tooltipEl.addEventListener('hidden.bs.tooltip', () => { + expect(spy).toHaveBeenCalled() + resolve() + }) + + tooltipEl.click() + }) + }) + }) + + describe('dispose', () => { + it('should destroy a tooltip', () => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const addEventSpy = spyOn(tooltipEl, 'addEventListener').and.callThrough() + const removeEventSpy = spyOn(tooltipEl, 'removeEventListener').and.callThrough() + + const tooltip = new Tooltip(tooltipEl) + + expect(Tooltip.getInstance(tooltipEl)).toEqual(tooltip) + + const expectedArgs = [ + ['mouseover', jasmine.any(Function), jasmine.any(Boolean)], + ['mouseout', jasmine.any(Function), jasmine.any(Boolean)], + ['focusin', jasmine.any(Function), jasmine.any(Boolean)], + ['focusout', jasmine.any(Function), jasmine.any(Boolean)] + ] + + expect(addEventSpy.calls.allArgs()).toEqual(expectedArgs) + + tooltip.dispose() + + expect(Tooltip.getInstance(tooltipEl)).toBeNull() + expect(removeEventSpy.calls.allArgs()).toEqual(expectedArgs) + }) + + it('should destroy a tooltip after it is shown and hidden', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + tooltipEl.addEventListener('shown.bs.tooltip', () => { + tooltip.hide() + }) + tooltipEl.addEventListener('hidden.bs.tooltip', () => { + tooltip.dispose() + expect(tooltip.tip).toBeNull() + expect(Tooltip.getInstance(tooltipEl)).toBeNull() + resolve() + }) + + tooltip.show() + }) + }) + + it('should destroy a tooltip and remove it from the dom', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + tooltipEl.addEventListener('shown.bs.tooltip', () => { + expect(document.querySelector('.tooltip')).not.toBeNull() + + tooltip.dispose() + + expect(document.querySelector('.tooltip')).toBeNull() + resolve() + }) + + tooltip.show() + }) + }) + + it('should destroy a tooltip and reset it\'s initial title', () => { + fixtureEl.innerHTML = [ + '', + '' + ].join('') + + const tooltipWithTitleEl = fixtureEl.querySelector('#tooltipWithTitle') + const tooltip = new Tooltip('#tooltipWithTitle') + expect(tooltipWithTitleEl.getAttribute('title')).toBeNull() + tooltip.dispose() + expect(tooltipWithTitleEl.getAttribute('title')).toBe('tooltipTitle') + + const tooltipWithoutTitleEl = fixtureEl.querySelector('#tooltipWithoutTitle') + const tooltip2 = new Tooltip('#tooltipWithTitle') + expect(tooltipWithoutTitleEl.getAttribute('title')).toBeNull() + tooltip2.dispose() + expect(tooltipWithoutTitleEl.getAttribute('title')).toBeNull() + }) + }) + + describe('show', () => { + it('should show a tooltip', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + tooltipEl.addEventListener('shown.bs.tooltip', () => { + const tooltipShown = document.querySelector('.tooltip') + + expect(tooltipShown).not.toBeNull() + expect(tooltipEl.getAttribute('aria-describedby')).toEqual(tooltipShown.getAttribute('id')) + expect(tooltipShown.getAttribute('id')).toContain('tooltip') + resolve() + }) + + tooltip.show() + }) + }) + + it('should show a tooltip when hovering a child element', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + ' ', + ' ', + ' ', + ' ', + '' + ].join('') + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + const spy = spyOn(tooltip, 'show') + + tooltipEl.querySelector('rect').dispatchEvent(createEvent('mouseover', { bubbles: true })) + + setTimeout(() => { + expect(spy).toHaveBeenCalled() + resolve() + }, 0) + }) + }) + + it('should show a tooltip on mobile', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + document.documentElement.ontouchstart = noop + + const spy = spyOn(EventHandler, 'on').and.callThrough() + + tooltipEl.addEventListener('shown.bs.tooltip', () => { + expect(document.querySelector('.tooltip')).not.toBeNull() + expect(spy).toHaveBeenCalledWith(jasmine.any(Object), 'mouseover', noop) + document.documentElement.ontouchstart = undefined + resolve() + }) + + tooltip.show() + }) + }) + + it('should show a tooltip relative to placement option', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl, { + placement: 'bottom' + }) + + tooltipEl.addEventListener('inserted.bs.tooltip', () => { + expect(tooltip._getTipElement()).toHaveClass('bs-tooltip-auto') + }) + + tooltipEl.addEventListener('shown.bs.tooltip', () => { + expect(tooltip._getTipElement()).toHaveClass('bs-tooltip-auto') + expect(tooltip._getTipElement().getAttribute('data-popper-placement')).toEqual('bottom') + resolve() + }) + + tooltip.show() + }) + }) + + it('should not error when trying to show a tooltip that has been removed from the dom', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + const firstCallback = () => { + tooltipEl.removeEventListener('shown.bs.tooltip', firstCallback) + let tooltipShown = document.querySelector('.tooltip') + + tooltipShown.remove() + + tooltipEl.addEventListener('shown.bs.tooltip', () => { + tooltipShown = document.querySelector('.tooltip') + + expect(tooltipShown).not.toBeNull() + resolve() + }) + + tooltip.show() + } + + tooltipEl.addEventListener('shown.bs.tooltip', firstCallback) + + tooltip.show() + }) + }) + + it('should show a tooltip with a dom element container', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl, { + container: fixtureEl + }) + + tooltipEl.addEventListener('shown.bs.tooltip', () => { + expect(fixtureEl.querySelector('.tooltip')).not.toBeNull() + resolve() + }) + + tooltip.show() + }) + }) + + it('should show a tooltip with a jquery element container', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl, { + container: { + 0: fixtureEl, + jquery: 'jQuery' + } + }) + + tooltipEl.addEventListener('shown.bs.tooltip', () => { + expect(fixtureEl.querySelector('.tooltip')).not.toBeNull() + resolve() + }) + + tooltip.show() + }) + }) + + it('should show a tooltip with a selector in container', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl, { + container: '#fixture' + }) + + tooltipEl.addEventListener('shown.bs.tooltip', () => { + expect(fixtureEl.querySelector('.tooltip')).not.toBeNull() + resolve() + }) + + tooltip.show() + }) + }) + + it('should show a tooltip with placement as a function', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const spy = jasmine.createSpy('placement').and.returnValue('top') + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl, { + placement: spy + }) + + tooltipEl.addEventListener('shown.bs.tooltip', () => { + expect(document.querySelector('.tooltip')).not.toBeNull() + expect(spy).toHaveBeenCalled() + resolve() + }) + + tooltip.show() + }) + }) + + it('should show a tooltip without the animation', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl, { + animation: false + }) + + tooltipEl.addEventListener('shown.bs.tooltip', () => { + const tip = document.querySelector('.tooltip') + + expect(tip).not.toBeNull() + expect(tip).not.toHaveClass('fade') + resolve() + }) + + tooltip.show() + }) + }) + + it('should throw an error the element is not visible', () => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + try { + tooltip.show() + } catch (error) { + expect(error.message).toEqual('Please use show on visible elements') + } + }) + + it('should not show a tooltip if show.bs.tooltip is prevented', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + const expectedDone = () => { + setTimeout(() => { + expect(document.querySelector('.tooltip')).toBeNull() + resolve() + }, 10) + } + + tooltipEl.addEventListener('show.bs.tooltip', ev => { + ev.preventDefault() + expectedDone() + }) + + tooltipEl.addEventListener('shown.bs.tooltip', () => { + reject(new Error('Tooltip should not be shown')) + }) + + tooltip.show() + }) + }) + + it('should show tooltip if leave event hasn\'t occurred before delay expires', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl, { + delay: 150 + }) + + const spy = spyOn(tooltip, 'show') + + setTimeout(() => { + expect(spy).not.toHaveBeenCalled() + }, 100) + + setTimeout(() => { + expect(spy).toHaveBeenCalled() + resolve() + }, 200) + + tooltipEl.dispatchEvent(createEvent('mouseover')) + }) + }) + + it('should not show tooltip if leave event occurs before delay expires', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl, { + delay: 150 + }) + + const spy = spyOn(tooltip, 'show') + + setTimeout(() => { + expect(spy).not.toHaveBeenCalled() + tooltipEl.dispatchEvent(createEvent('mouseover')) + }, 100) + + setTimeout(() => { + expect(spy).toHaveBeenCalled() + expect(document.querySelectorAll('.tooltip')).toHaveSize(0) + resolve() + }, 200) + + tooltipEl.dispatchEvent(createEvent('mouseover')) + }) + }) + + it('should not hide tooltip if leave event occurs and enter event occurs within the hide delay', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + expect(tooltip._config.delay).toEqual({ show: 0, hide: 150 }) + + setTimeout(() => { + expect(tooltip._getTipElement()).toHaveClass('show') + tooltipEl.dispatchEvent(createEvent('mouseout')) + + setTimeout(() => { + expect(tooltip._getTipElement()).toHaveClass('show') + tooltipEl.dispatchEvent(createEvent('mouseover')) + }, 100) + + setTimeout(() => { + expect(tooltip._getTipElement()).toHaveClass('show') + expect(document.querySelectorAll('.tooltip')).toHaveSize(1) + resolve() + }, 200) + }, 10) + + tooltipEl.dispatchEvent(createEvent('mouseover')) + }) + }) + + it('should not hide tooltip if leave event occurs and interaction remains inside trigger', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + 'Trigger', + 'the tooltip', + '' + ].join('') + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + const triggerChild = tooltipEl.querySelector('b') + + const spy = spyOn(tooltip, 'hide').and.callThrough() + + tooltipEl.addEventListener('mouseover', () => { + const moveMouseToChildEvent = createEvent('mouseout') + Object.defineProperty(moveMouseToChildEvent, 'relatedTarget', { + value: triggerChild + }) + + tooltipEl.dispatchEvent(moveMouseToChildEvent) + }) + + tooltipEl.addEventListener('mouseout', () => { + expect(spy).not.toHaveBeenCalled() + resolve() + }) + + tooltipEl.dispatchEvent(createEvent('mouseover')) + }) + }) + + it('should properly maintain tooltip state if leave event occurs and enter event occurs during hide transition', () => { + return new Promise(resolve => { + // Style this tooltip to give it plenty of room for popper to do what it wants + fixtureEl.innerHTML = 'Trigger' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + spyOn(window, 'getComputedStyle').and.returnValue({ + transitionDuration: '0.15s', + transitionDelay: '0s' + }) + + setTimeout(() => { + expect(tooltip._popper).not.toBeNull() + expect(tooltip._getTipElement().getAttribute('data-popper-placement')).toEqual('top') + tooltipEl.dispatchEvent(createEvent('mouseout')) + + setTimeout(() => { + expect(tooltip._getTipElement()).not.toHaveClass('show') + tooltipEl.dispatchEvent(createEvent('mouseover')) + }, 100) + + setTimeout(() => { + expect(tooltip._popper).not.toBeNull() + expect(tooltip._getTipElement().getAttribute('data-popper-placement')).toEqual('top') + resolve() + }, 200) + }, 10) + + tooltipEl.dispatchEvent(createEvent('mouseover')) + }) + }) + + it('should only trigger inserted event if a new tooltip element was created', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + spyOn(window, 'getComputedStyle').and.returnValue({ + transitionDuration: '0.15s', + transitionDelay: '0s' + }) + + const insertedFunc = jasmine.createSpy() + tooltipEl.addEventListener('inserted.bs.tooltip', insertedFunc) + + setTimeout(() => { + expect(insertedFunc).toHaveBeenCalledTimes(1) + tooltip.hide() + + setTimeout(() => { + tooltip.show() + }, 100) + + setTimeout(() => { + expect(insertedFunc).toHaveBeenCalledTimes(2) + resolve() + }, 200) + }, 0) + + tooltip.show() + }) + }) + + it('should show a tooltip with custom class provided in data attributes', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + tooltipEl.addEventListener('shown.bs.tooltip', () => { + const tip = document.querySelector('.tooltip') + expect(tip).not.toBeNull() + expect(tip).toHaveClass('custom-class') + resolve() + }) + + tooltip.show() + }) + }) + + it('should show a tooltip with custom class provided as a string in config', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl, { + customClass: 'custom-class custom-class-2' + }) + + tooltipEl.addEventListener('shown.bs.tooltip', () => { + const tip = document.querySelector('.tooltip') + expect(tip).not.toBeNull() + expect(tip).toHaveClass('custom-class') + expect(tip).toHaveClass('custom-class-2') + resolve() + }) + + tooltip.show() + }) + }) + + it('should show a tooltip with custom class provided as a function in config', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const spy = jasmine.createSpy('customClass').and.returnValue('custom-class') + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl, { + customClass: spy + }) + + tooltipEl.addEventListener('shown.bs.tooltip', () => { + const tip = document.querySelector('.tooltip') + expect(tip).not.toBeNull() + expect(spy).toHaveBeenCalled() + expect(tip).toHaveClass('custom-class') + resolve() + }) + + tooltip.show() + }) + }) + + it('should remove `title` attribute if exists', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + tooltipEl.addEventListener('shown.bs.tooltip', () => { + expect(tooltipEl.getAttribute('title')).toBeNull() + resolve() + }) + tooltip.show() + }) + }) + }) + + describe('hide', () => { + it('should hide a tooltip', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + tooltipEl.addEventListener('shown.bs.tooltip', () => tooltip.hide()) + tooltipEl.addEventListener('hidden.bs.tooltip', () => { + expect(document.querySelector('.tooltip')).toBeNull() + expect(tooltipEl.getAttribute('aria-describedby')).toBeNull() + resolve() + }) + + tooltip.show() + }) + }) + + it('should hide a tooltip on mobile', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + const spy = spyOn(EventHandler, 'off') + + tooltipEl.addEventListener('shown.bs.tooltip', () => { + document.documentElement.ontouchstart = noop + tooltip.hide() + }) + + tooltipEl.addEventListener('hidden.bs.tooltip', () => { + expect(document.querySelector('.tooltip')).toBeNull() + expect(spy).toHaveBeenCalledWith(jasmine.any(Object), 'mouseover', noop) + document.documentElement.ontouchstart = undefined + resolve() + }) + + tooltip.show() + }) + }) + + it('should hide a tooltip without animation', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl, { + animation: false + }) + + tooltipEl.addEventListener('shown.bs.tooltip', () => tooltip.hide()) + tooltipEl.addEventListener('hidden.bs.tooltip', () => { + expect(document.querySelector('.tooltip')).toBeNull() + expect(tooltipEl.getAttribute('aria-describedby')).toBeNull() + resolve() + }) + + tooltip.show() + }) + }) + + it('should not hide a tooltip if hide event is prevented', () => { + return new Promise((resolve, reject) => { + fixtureEl.innerHTML = '' + + const assertDone = () => { + setTimeout(() => { + expect(document.querySelector('.tooltip')).not.toBeNull() + resolve() + }, 20) + } + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl, { + animation: false + }) + + tooltipEl.addEventListener('shown.bs.tooltip', () => tooltip.hide()) + tooltipEl.addEventListener('hide.bs.tooltip', event => { + event.preventDefault() + assertDone() + }) + tooltipEl.addEventListener('hidden.bs.tooltip', () => { + reject(new Error('should not trigger hidden event')) + }) + + tooltip.show() + }) + }) + + it('should not throw error running hide if popper hasn\'t been shown', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const tooltip = new Tooltip(div) + + try { + tooltip.hide() + expect().nothing() + } catch { + throw new Error('should not throw error') + } + }) + }) + + describe('update', () => { + it('should call popper update', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + tooltipEl.addEventListener('shown.bs.tooltip', () => { + const spy = spyOn(tooltip._popper, 'update') + + tooltip.update() + + expect(spy).toHaveBeenCalled() + resolve() + }) + + tooltip.show() + }) + }) + + it('should do nothing if the tooltip is not shown', () => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + tooltip.update() + expect().nothing() + }) + }) + + describe('_isWithContent', () => { + it('should return true if there is content', () => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + expect(tooltip._isWithContent()).toBeTrue() + }) + + it('should return false if there is no content', () => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + expect(tooltip._isWithContent()).toBeFalse() + }) + }) + + describe('_getTipElement', () => { + it('should create the tip element and return it', () => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + const spy = spyOn(document, 'createElement').and.callThrough() + + expect(tooltip._getTipElement()).toBeDefined() + expect(spy).toHaveBeenCalled() + }) + + it('should return the created tip element', () => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + const spy = spyOn(document, 'createElement').and.callThrough() + + expect(tooltip._getTipElement()).toBeDefined() + expect(spy).toHaveBeenCalled() + + spy.calls.reset() + + expect(tooltip._getTipElement()).toBeDefined() + expect(spy).not.toHaveBeenCalled() + }) + }) + + describe('setContent', () => { + it('should set tip content', () => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl, { animation: false }) + + const tip = tooltip._getTipElement() + + tooltip.setContent(tip) + + expect(tip).not.toHaveClass('show') + expect(tip).not.toHaveClass('fade') + expect(tip.querySelector('.tooltip-inner').textContent).toEqual('Another tooltip') + }) + + it('should re-show tip if it was already shown', () => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + tooltip.show() + const tip = () => tooltip._getTipElement() + + expect(tip()).toHaveClass('show') + tooltip.setContent({ '.tooltip-inner': 'foo' }) + + expect(tip()).toHaveClass('show') + expect(tip().querySelector('.tooltip-inner').textContent).toEqual('foo') + }) + + it('should keep tip hidden, if it was already hidden before', () => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + const tip = () => tooltip._getTipElement() + + expect(tip()).not.toHaveClass('show') + tooltip.setContent({ '.tooltip-inner': 'foo' }) + + expect(tip()).not.toHaveClass('show') + tooltip.show() + expect(tip().querySelector('.tooltip-inner').textContent).toEqual('foo') + }) + + it('"setContent" should keep the initial template', () => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + tooltip.setContent({ '.tooltip-inner': 'foo' }) + const tip = tooltip._getTipElement() + + expect(tip).toHaveClass('tooltip') + expect(tip).toHaveClass('bs-tooltip-auto') + expect(tip.querySelector('.tooltip-arrow')).not.toBeNull() + expect(tip.querySelector('.tooltip-inner')).not.toBeNull() + }) + }) + + describe('setContent', () => { + it('should do nothing if the element is null', () => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + tooltip.setContent({ '.tooltip': null }) + expect().nothing() + }) + + it('should do nothing if the content is a child of the element', () => { + fixtureEl.innerHTML = [ + '', + '
', + '
' + ].join('') + + const tooltipEl = fixtureEl.querySelector('a') + const childContent = fixtureEl.querySelector('div') + const tooltip = new Tooltip(tooltipEl, { + html: true + }) + + tooltip._getTipElement().append(childContent) + tooltip.setContent({ '.tooltip': childContent }) + + expect().nothing() + }) + + it('should add the content as a child of the element for jQuery elements', () => { + fixtureEl.innerHTML = [ + '', + '
', + '
' + ].join('') + + const tooltipEl = fixtureEl.querySelector('a') + const childContent = fixtureEl.querySelector('div') + const tooltip = new Tooltip(tooltipEl, { + html: true + }) + + tooltip.setContent({ '.tooltip': { 0: childContent, jquery: 'jQuery' } }) + tooltip.show() + + expect(childContent.parentNode).toEqual(tooltip._getTipElement()) + }) + + it('should add the child text content in the element', () => { + fixtureEl.innerHTML = [ + '', + '
Tooltip
', + '
' + ].join('') + + const tooltipEl = fixtureEl.querySelector('a') + const childContent = fixtureEl.querySelector('div') + const tooltip = new Tooltip(tooltipEl) + + tooltip.setContent({ '.tooltip': childContent }) + + expect(childContent.textContent).toEqual(tooltip._getTipElement().textContent) + }) + + it('should add html without sanitize it', () => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl, { + sanitize: false, + html: true + }) + + tooltip.setContent({ '.tooltip': '
Tooltip
' }) + + expect(tooltip._getTipElement().querySelector('div').id).toEqual('childContent') + }) + + it('should add html sanitized', () => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl, { + html: true + }) + + const content = [ + '
', + ' ', + '
' + ].join('') + + tooltip.setContent({ '.tooltip': content }) + expect(tooltip._getTipElement().querySelector('div').id).toEqual('childContent') + expect(tooltip._getTipElement().querySelector('button')).toBeNull() + }) + + it('should add text content', () => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + tooltip.setContent({ '.tooltip': 'test' }) + + expect(tooltip._getTipElement().textContent).toEqual('test') + }) + }) + + describe('_getTitle', () => { + it('should return the title', () => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + expect(tooltip._getTitle()).toEqual('Another tooltip') + }) + + it('should call title function', () => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl, { + title: () => 'test' + }) + + expect(tooltip._getTitle()).toEqual('test') + }) + }) + + describe('getInstance', () => { + it('should return tooltip instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const alert = new Tooltip(div) + + expect(Tooltip.getInstance(div)).toEqual(alert) + expect(Tooltip.getInstance(div)).toBeInstanceOf(Tooltip) + }) + + it('should return null when there is no tooltip instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(Tooltip.getInstance(div)).toBeNull() + }) + }) + + describe('aria-label', () => { + it('should add the aria-label attribute for referencing original title', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + tooltipEl.addEventListener('shown.bs.tooltip', () => { + const tooltipShown = document.querySelector('.tooltip') + + expect(tooltipShown).not.toBeNull() + expect(tooltipEl.getAttribute('aria-label')).toEqual('Another tooltip') + resolve() + }) + + tooltip.show() + }) + }) + + it('should add the aria-label attribute when element text content is a whitespace string', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = ' ' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + tooltipEl.addEventListener('shown.bs.tooltip', () => { + const tooltipShown = document.querySelector('.tooltip') + + expect(tooltipShown).not.toBeNull() + expect(tooltipEl.getAttribute('aria-label')).toEqual('A tooltip') + resolve() + }) + + tooltip.show() + }) + }) + + it('should not add the aria-label attribute if the attribute already exists', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + tooltipEl.addEventListener('shown.bs.tooltip', () => { + const tooltipShown = document.querySelector('.tooltip') + + expect(tooltipShown).not.toBeNull() + expect(tooltipEl.getAttribute('aria-label')).toEqual('Different label') + resolve() + }) + + tooltip.show() + }) + }) + + it('should not add the aria-label attribute if the element has text content', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = 'text content' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + tooltipEl.addEventListener('shown.bs.tooltip', () => { + const tooltipShown = document.querySelector('.tooltip') + + expect(tooltipShown).not.toBeNull() + expect(tooltipEl.getAttribute('aria-label')).toBeNull() + resolve() + }) + + tooltip.show() + }) + }) + }) + + describe('getOrCreateInstance', () => { + it('should return tooltip instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const tooltip = new Tooltip(div) + + expect(Tooltip.getOrCreateInstance(div)).toEqual(tooltip) + expect(Tooltip.getInstance(div)).toEqual(Tooltip.getOrCreateInstance(div, {})) + expect(Tooltip.getOrCreateInstance(div)).toBeInstanceOf(Tooltip) + }) + + it('should return new instance when there is no tooltip instance', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(Tooltip.getInstance(div)).toBeNull() + expect(Tooltip.getOrCreateInstance(div)).toBeInstanceOf(Tooltip) + }) + + it('should return new instance when there is no tooltip instance with given configuration', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(Tooltip.getInstance(div)).toBeNull() + const tooltip = Tooltip.getOrCreateInstance(div, { + title: () => 'test' + }) + expect(tooltip).toBeInstanceOf(Tooltip) + + expect(tooltip._getTitle()).toEqual('test') + }) + + it('should return the instance when exists without given configuration', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const tooltip = new Tooltip(div, { + title: () => 'nothing' + }) + expect(Tooltip.getInstance(div)).toEqual(tooltip) + + const tooltip2 = Tooltip.getOrCreateInstance(div, { + title: () => 'test' + }) + expect(tooltip).toBeInstanceOf(Tooltip) + expect(tooltip2).toEqual(tooltip) + + expect(tooltip2._getTitle()).toEqual('nothing') + }) + }) + + describe('jQueryInterface', () => { + it('should create a tooltip', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + jQueryMock.fn.tooltip = Tooltip.jQueryInterface + jQueryMock.elements = [div] + + jQueryMock.fn.tooltip.call(jQueryMock) + + expect(Tooltip.getInstance(div)).not.toBeNull() + }) + + it('should not re create a tooltip', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const tooltip = new Tooltip(div) + + jQueryMock.fn.tooltip = Tooltip.jQueryInterface + jQueryMock.elements = [div] + + jQueryMock.fn.tooltip.call(jQueryMock) + + expect(Tooltip.getInstance(div)).toEqual(tooltip) + }) + + it('should call a tooltip method', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const tooltip = new Tooltip(div) + + const spy = spyOn(tooltip, 'show') + + jQueryMock.fn.tooltip = Tooltip.jQueryInterface + jQueryMock.elements = [div] + + jQueryMock.fn.tooltip.call(jQueryMock, 'show') + + expect(Tooltip.getInstance(div)).toEqual(tooltip) + expect(spy).toHaveBeenCalled() + }) + + it('should throw error on undefined method', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const action = 'undefinedMethod' + + jQueryMock.fn.tooltip = Tooltip.jQueryInterface + jQueryMock.elements = [div] + + expect(() => { + jQueryMock.fn.tooltip.call(jQueryMock, action) + }).toThrowError(TypeError, `No method named "${action}"`) + }) + }) +}) diff --git a/js/tests/unit/util/backdrop.spec.js b/js/tests/unit/util/backdrop.spec.js new file mode 100644 index 0000000..73384fc --- /dev/null +++ b/js/tests/unit/util/backdrop.spec.js @@ -0,0 +1,321 @@ +import Backdrop from '../../../src/util/backdrop' +import { getTransitionDurationFromElement } from '../../../src/util/index' +import { clearFixture, getFixture } from '../../helpers/fixture' + +const CLASS_BACKDROP = '.modal-backdrop' +const CLASS_NAME_FADE = 'fade' +const CLASS_NAME_SHOW = 'show' + +describe('Backdrop', () => { + let fixtureEl + + beforeAll(() => { + fixtureEl = getFixture() + }) + + afterEach(() => { + clearFixture() + const list = document.querySelectorAll(CLASS_BACKDROP) + + for (const el of list) { + el.remove() + } + }) + + describe('show', () => { + it('should append the backdrop html once on show and include the "show" class if it is "shown"', () => { + return new Promise(resolve => { + const instance = new Backdrop({ + isVisible: true, + isAnimated: false + }) + const getElements = () => document.querySelectorAll(CLASS_BACKDROP) + + expect(getElements()).toHaveSize(0) + + instance.show() + instance.show(() => { + expect(getElements()).toHaveSize(1) + for (const el of getElements()) { + expect(el).toHaveClass(CLASS_NAME_SHOW) + } + + resolve() + }) + }) + }) + + it('should not append the backdrop html if it is not "shown"', () => { + return new Promise(resolve => { + const instance = new Backdrop({ + isVisible: false, + isAnimated: true + }) + const getElements = () => document.querySelectorAll(CLASS_BACKDROP) + + expect(getElements()).toHaveSize(0) + instance.show(() => { + expect(getElements()).toHaveSize(0) + resolve() + }) + }) + }) + + it('should append the backdrop html once and include the "fade" class if it is "shown" and "animated"', () => { + return new Promise(resolve => { + const instance = new Backdrop({ + isVisible: true, + isAnimated: true + }) + const getElements = () => document.querySelectorAll(CLASS_BACKDROP) + + expect(getElements()).toHaveSize(0) + + instance.show(() => { + expect(getElements()).toHaveSize(1) + for (const el of getElements()) { + expect(el).toHaveClass(CLASS_NAME_FADE) + } + + resolve() + }) + }) + }) + }) + + describe('hide', () => { + it('should remove the backdrop html', () => { + return new Promise(resolve => { + const instance = new Backdrop({ + isVisible: true, + isAnimated: true + }) + + const getElements = () => document.body.querySelectorAll(CLASS_BACKDROP) + + expect(getElements()).toHaveSize(0) + instance.show(() => { + expect(getElements()).toHaveSize(1) + instance.hide(() => { + expect(getElements()).toHaveSize(0) + resolve() + }) + }) + }) + }) + + it('should remove the "show" class', () => { + return new Promise(resolve => { + const instance = new Backdrop({ + isVisible: true, + isAnimated: true + }) + const elem = instance._getElement() + + instance.show() + instance.hide(() => { + expect(elem).not.toHaveClass(CLASS_NAME_SHOW) + resolve() + }) + }) + }) + + it('should not try to remove Node on remove method if it is not "shown"', () => { + return new Promise(resolve => { + const instance = new Backdrop({ + isVisible: false, + isAnimated: true + }) + const getElements = () => document.querySelectorAll(CLASS_BACKDROP) + const spy = spyOn(instance, 'dispose').and.callThrough() + + expect(getElements()).toHaveSize(0) + expect(instance._isAppended).toBeFalse() + instance.show(() => { + instance.hide(() => { + expect(getElements()).toHaveSize(0) + expect(spy).not.toHaveBeenCalled() + expect(instance._isAppended).toBeFalse() + resolve() + }) + }) + }) + }) + + it('should not error if the backdrop no longer has a parent', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + + const wrapper = fixtureEl.querySelector('#wrapper') + const instance = new Backdrop({ + isVisible: true, + isAnimated: true, + rootElement: wrapper + }) + + const getElements = () => document.querySelectorAll(CLASS_BACKDROP) + + instance.show(() => { + wrapper.remove() + instance.hide(() => { + expect(getElements()).toHaveSize(0) + resolve() + }) + }) + }) + }) + }) + + describe('click callback', () => { + it('should execute callback on click', () => { + return new Promise(resolve => { + const spy = jasmine.createSpy('spy') + + const instance = new Backdrop({ + isVisible: true, + isAnimated: false, + clickCallback: () => spy() + }) + const endTest = () => { + setTimeout(() => { + expect(spy).toHaveBeenCalled() + resolve() + }, 10) + } + + instance.show(() => { + const clickEvent = new Event('mousedown', { bubbles: true, cancelable: true }) + document.querySelector(CLASS_BACKDROP).dispatchEvent(clickEvent) + endTest() + }) + }) + }) + + describe('animation callbacks', () => { + it('should show and hide backdrop after counting transition duration if it is animated', () => { + return new Promise(resolve => { + const instance = new Backdrop({ + isVisible: true, + isAnimated: true + }) + const spy2 = jasmine.createSpy('spy2') + + const execDone = () => { + setTimeout(() => { + expect(spy2).toHaveBeenCalledTimes(2) + resolve() + }, 10) + } + + instance.show(spy2) + instance.hide(() => { + spy2() + execDone() + }) + expect(spy2).not.toHaveBeenCalled() + }) + }) + + it('should show and hide backdrop without a delay if it is not animated', () => { + return new Promise(resolve => { + const spy = jasmine.createSpy('spy', getTransitionDurationFromElement) + const instance = new Backdrop({ + isVisible: true, + isAnimated: false + }) + const spy2 = jasmine.createSpy('spy2') + + instance.show(spy2) + instance.hide(spy2) + + setTimeout(() => { + expect(spy2).toHaveBeenCalled() + expect(spy).not.toHaveBeenCalled() + resolve() + }, 10) + }) + }) + + it('should not call delay callbacks if it is not "shown"', () => { + return new Promise(resolve => { + const instance = new Backdrop({ + isVisible: false, + isAnimated: true + }) + const spy = jasmine.createSpy('spy', getTransitionDurationFromElement) + + instance.show() + instance.hide(() => { + expect(spy).not.toHaveBeenCalled() + resolve() + }) + }) + }) + }) + + describe('Config', () => { + describe('rootElement initialization', () => { + it('should be appended on "document.body" by default', () => { + return new Promise(resolve => { + const instance = new Backdrop({ + isVisible: true + }) + const getElement = () => document.querySelector(CLASS_BACKDROP) + instance.show(() => { + expect(getElement().parentElement).toEqual(document.body) + resolve() + }) + }) + }) + + it('should find the rootElement if passed as a string', () => { + return new Promise(resolve => { + const instance = new Backdrop({ + isVisible: true, + rootElement: 'body' + }) + const getElement = () => document.querySelector(CLASS_BACKDROP) + instance.show(() => { + expect(getElement().parentElement).toEqual(document.body) + resolve() + }) + }) + }) + + it('should be appended on any element given by the proper config', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + + const wrapper = fixtureEl.querySelector('#wrapper') + const instance = new Backdrop({ + isVisible: true, + rootElement: wrapper + }) + const getElement = () => document.querySelector(CLASS_BACKDROP) + instance.show(() => { + expect(getElement().parentElement).toEqual(wrapper) + resolve() + }) + }) + }) + }) + + describe('ClassName', () => { + it('should allow configuring className', () => { + return new Promise(resolve => { + const instance = new Backdrop({ + isVisible: true, + className: 'foo' + }) + const getElement = () => document.querySelector('.foo') + instance.show(() => { + expect(getElement()).toEqual(instance._getElement()) + instance.dispose() + resolve() + }) + }) + }) + }) + }) + }) +}) diff --git a/js/tests/unit/util/component-functions.spec.js b/js/tests/unit/util/component-functions.spec.js new file mode 100644 index 0000000..ec36672 --- /dev/null +++ b/js/tests/unit/util/component-functions.spec.js @@ -0,0 +1,108 @@ +/* Test helpers */ + +import { clearFixture, createEvent, getFixture } from '../../helpers/fixture' +import { enableDismissTrigger } from '../../../src/util/component-functions' +import BaseComponent from '../../../src/base-component' + +class DummyClass2 extends BaseComponent { + static get NAME() { + return 'test' + } + + hide() { + return true + } + + testMethod() { + return true + } +} + +describe('Plugin functions', () => { + let fixtureEl + + beforeAll(() => { + fixtureEl = getFixture() + }) + + afterEach(() => { + clearFixture() + }) + + describe('data-bs-dismiss functionality', () => { + it('should get Plugin and execute the given method, when a click occurred on data-bs-dismiss="PluginName"', () => { + fixtureEl.innerHTML = [ + '
', + ' ', + '
' + ].join('') + + const spyGet = spyOn(DummyClass2, 'getOrCreateInstance').and.callThrough() + const spyTest = spyOn(DummyClass2.prototype, 'testMethod') + const componentWrapper = fixtureEl.querySelector('#foo') + const btnClose = fixtureEl.querySelector('[data-bs-dismiss="test"]') + const event = createEvent('click') + + enableDismissTrigger(DummyClass2, 'testMethod') + btnClose.dispatchEvent(event) + + expect(spyGet).toHaveBeenCalledWith(componentWrapper) + expect(spyTest).toHaveBeenCalled() + }) + + it('if data-bs-dismiss="PluginName" hasn\'t got "data-bs-target", "getOrCreateInstance" has to be initialized by closest "plugin.Name" class', () => { + fixtureEl.innerHTML = [ + '
', + ' ', + '
' + ].join('') + + const spyGet = spyOn(DummyClass2, 'getOrCreateInstance').and.callThrough() + const spyHide = spyOn(DummyClass2.prototype, 'hide') + const componentWrapper = fixtureEl.querySelector('#foo') + const btnClose = fixtureEl.querySelector('[data-bs-dismiss="test"]') + const event = createEvent('click') + + enableDismissTrigger(DummyClass2) + btnClose.dispatchEvent(event) + + expect(spyGet).toHaveBeenCalledWith(componentWrapper) + expect(spyHide).toHaveBeenCalled() + }) + + it('if data-bs-dismiss="PluginName" is disabled, must not trigger function', () => { + fixtureEl.innerHTML = [ + '
', + ' ', + '
' + ].join('') + + const spy = spyOn(DummyClass2, 'getOrCreateInstance').and.callThrough() + const btnClose = fixtureEl.querySelector('[data-bs-dismiss="test"]') + const event = createEvent('click') + + enableDismissTrigger(DummyClass2) + btnClose.dispatchEvent(event) + + expect(spy).not.toHaveBeenCalled() + }) + + it('should prevent default when the trigger is or ', () => { + fixtureEl.innerHTML = [ + '
', + ' ', + '
' + ].join('') + + const btnClose = fixtureEl.querySelector('[data-bs-dismiss="test"]') + const event = createEvent('click') + + enableDismissTrigger(DummyClass2) + const spy = spyOn(Event.prototype, 'preventDefault').and.callThrough() + + btnClose.dispatchEvent(event) + + expect(spy).toHaveBeenCalled() + }) + }) +}) diff --git a/js/tests/unit/util/config.spec.js b/js/tests/unit/util/config.spec.js new file mode 100644 index 0000000..e1693c0 --- /dev/null +++ b/js/tests/unit/util/config.spec.js @@ -0,0 +1,166 @@ +import Config from '../../../src/util/config' +import { clearFixture, getFixture } from '../../helpers/fixture' + +class DummyConfigClass extends Config { + static get NAME() { + return 'dummy' + } +} + +describe('Config', () => { + let fixtureEl + const name = 'dummy' + + beforeAll(() => { + fixtureEl = getFixture() + }) + + afterEach(() => { + clearFixture() + }) + + describe('NAME', () => { + it('should return plugin NAME', () => { + expect(DummyConfigClass.NAME).toEqual(name) + }) + }) + + describe('DefaultType', () => { + it('should return plugin default type', () => { + expect(DummyConfigClass.DefaultType).toEqual(jasmine.any(Object)) + }) + }) + + describe('Default', () => { + it('should return plugin defaults', () => { + expect(DummyConfigClass.Default).toEqual(jasmine.any(Object)) + }) + }) + + describe('mergeConfigObj', () => { + it('should parse element\'s data attributes and merge it with default config. Element\'s data attributes must excel Defaults', () => { + fixtureEl.innerHTML = '
' + + spyOnProperty(DummyConfigClass, 'Default', 'get').and.returnValue({ + testBool: true, + testString: 'foo', + testString1: 'foo', + testInt: 7 + }) + const instance = new DummyConfigClass() + const configResult = instance._mergeConfigObj({}, fixtureEl.querySelector('#test')) + + expect(configResult.testBool).toEqual(false) + expect(configResult.testString).toEqual('foo') + expect(configResult.testString1).toEqual('bar') + expect(configResult.testInt).toEqual(8) + }) + + it('should parse element\'s data attributes and merge it with default config, plug these given during method call. The programmatically given should excel all', () => { + fixtureEl.innerHTML = '
' + + spyOnProperty(DummyConfigClass, 'Default', 'get').and.returnValue({ + testBool: true, + testString: 'foo', + testString1: 'foo', + testInt: 7 + }) + const instance = new DummyConfigClass() + const configResult = instance._mergeConfigObj({ + testString1: 'test', + testInt: 3 + }, fixtureEl.querySelector('#test')) + + expect(configResult.testBool).toEqual(false) + expect(configResult.testString).toEqual('foo') + expect(configResult.testString1).toEqual('test') + expect(configResult.testInt).toEqual(3) + }) + + it('should parse element\'s data attribute `config` and any rest attributes. The programmatically given should excel all. Data attribute `config` should excel only Defaults', () => { + fixtureEl.innerHTML = '
' + + spyOnProperty(DummyConfigClass, 'Default', 'get').and.returnValue({ + testBool: true, + testString: 'foo', + testString1: 'foo', + testInt: 7, + testInt2: 600 + }) + const instance = new DummyConfigClass() + const configResult = instance._mergeConfigObj({ + testString1: 'test' + }, fixtureEl.querySelector('#test')) + + expect(configResult.testBool).toEqual(false) + expect(configResult.testString).toEqual('foo') + expect(configResult.testString1).toEqual('test') + expect(configResult.testInt).toEqual(8) + expect(configResult.testInt2).toEqual(100) + }) + + it('should omit element\'s data attribute `config` if is not an object', () => { + fixtureEl.innerHTML = '
' + + spyOnProperty(DummyConfigClass, 'Default', 'get').and.returnValue({ + testInt: 7, + testInt2: 79 + }) + const instance = new DummyConfigClass() + const configResult = instance._mergeConfigObj({}, fixtureEl.querySelector('#test')) + + expect(configResult.testInt).toEqual(8) + expect(configResult.testInt2).toEqual(79) + }) + }) + + describe('typeCheckConfig', () => { + it('should check type of the config object', () => { + spyOnProperty(DummyConfigClass, 'DefaultType', 'get').and.returnValue({ + toggle: 'boolean', + parent: '(string|element)' + }) + const config = { + toggle: true, + parent: 777 + } + + const obj = new DummyConfigClass() + expect(() => { + obj._typeCheckConfig(config) + }).toThrowError(TypeError, obj.constructor.NAME.toUpperCase() + ': Option "parent" provided type "number" but expected type "(string|element)".') + }) + + it('should return null stringified when null is passed', () => { + spyOnProperty(DummyConfigClass, 'DefaultType', 'get').and.returnValue({ + toggle: 'boolean', + parent: '(null|element)' + }) + + const obj = new DummyConfigClass() + const config = { + toggle: true, + parent: null + } + + obj._typeCheckConfig(config) + expect().nothing() + }) + + it('should return undefined stringified when undefined is passed', () => { + spyOnProperty(DummyConfigClass, 'DefaultType', 'get').and.returnValue({ + toggle: 'boolean', + parent: '(undefined|element)' + }) + + const obj = new DummyConfigClass() + const config = { + toggle: true, + parent: undefined + } + + obj._typeCheckConfig(config) + expect().nothing() + }) + }) +}) diff --git a/js/tests/unit/util/focustrap.spec.js b/js/tests/unit/util/focustrap.spec.js new file mode 100644 index 0000000..bedd124 --- /dev/null +++ b/js/tests/unit/util/focustrap.spec.js @@ -0,0 +1,218 @@ +import FocusTrap from '../../../src/util/focustrap' +import EventHandler from '../../../src/dom/event-handler' +import SelectorEngine from '../../../src/dom/selector-engine' +import { clearFixture, createEvent, getFixture } from '../../helpers/fixture' + +describe('FocusTrap', () => { + let fixtureEl + + beforeAll(() => { + fixtureEl = getFixture() + }) + + afterEach(() => { + clearFixture() + }) + + describe('activate', () => { + it('should autofocus itself by default', () => { + fixtureEl.innerHTML = '
' + + const trapElement = fixtureEl.querySelector('div') + + const spy = spyOn(trapElement, 'focus') + + const focustrap = new FocusTrap({ trapElement }) + focustrap.activate() + + expect(spy).toHaveBeenCalled() + }) + + it('if configured not to autofocus, should not autofocus itself', () => { + fixtureEl.innerHTML = '
' + + const trapElement = fixtureEl.querySelector('div') + + const spy = spyOn(trapElement, 'focus') + + const focustrap = new FocusTrap({ trapElement, autofocus: false }) + focustrap.activate() + + expect(spy).not.toHaveBeenCalled() + }) + + it('should force focus inside focus trap if it can', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + 'outside', + '
', + ' inside', + '
' + ].join('') + + const trapElement = fixtureEl.querySelector('div') + const focustrap = new FocusTrap({ trapElement }) + focustrap.activate() + + const inside = document.getElementById('inside') + + const focusInListener = () => { + expect(spy).toHaveBeenCalled() + document.removeEventListener('focusin', focusInListener) + resolve() + } + + const spy = spyOn(inside, 'focus') + spyOn(SelectorEngine, 'focusableChildren').and.callFake(() => [inside]) + + document.addEventListener('focusin', focusInListener) + + const focusInEvent = createEvent('focusin', { bubbles: true }) + Object.defineProperty(focusInEvent, 'target', { + value: document.getElementById('outside') + }) + + document.dispatchEvent(focusInEvent) + }) + }) + + it('should wrap focus around forward on tab', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + 'outside', + '
', + ' first', + ' inside', + ' last', + '
' + ].join('') + + const trapElement = fixtureEl.querySelector('div') + const focustrap = new FocusTrap({ trapElement }) + focustrap.activate() + + const first = document.getElementById('first') + const inside = document.getElementById('inside') + const last = document.getElementById('last') + const outside = document.getElementById('outside') + + spyOn(SelectorEngine, 'focusableChildren').and.callFake(() => [first, inside, last]) + const spy = spyOn(first, 'focus').and.callThrough() + + const focusInListener = () => { + expect(spy).toHaveBeenCalled() + first.removeEventListener('focusin', focusInListener) + resolve() + } + + first.addEventListener('focusin', focusInListener) + + const keydown = createEvent('keydown') + keydown.key = 'Tab' + + document.dispatchEvent(keydown) + outside.focus() + }) + }) + + it('should wrap focus around backwards on shift-tab', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + 'outside', + '
', + ' first', + ' inside', + ' last', + '
' + ].join('') + + const trapElement = fixtureEl.querySelector('div') + const focustrap = new FocusTrap({ trapElement }) + focustrap.activate() + + const first = document.getElementById('first') + const inside = document.getElementById('inside') + const last = document.getElementById('last') + const outside = document.getElementById('outside') + + spyOn(SelectorEngine, 'focusableChildren').and.callFake(() => [first, inside, last]) + const spy = spyOn(last, 'focus').and.callThrough() + + const focusInListener = () => { + expect(spy).toHaveBeenCalled() + last.removeEventListener('focusin', focusInListener) + resolve() + } + + last.addEventListener('focusin', focusInListener) + + const keydown = createEvent('keydown') + keydown.key = 'Tab' + keydown.shiftKey = true + + document.dispatchEvent(keydown) + outside.focus() + }) + }) + + it('should force focus on itself if there is no focusable content', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + 'outside', + '
' + ].join('') + + const trapElement = fixtureEl.querySelector('div') + const focustrap = new FocusTrap({ trapElement }) + focustrap.activate() + + const focusInListener = () => { + expect(spy).toHaveBeenCalled() + document.removeEventListener('focusin', focusInListener) + resolve() + } + + const spy = spyOn(focustrap._config.trapElement, 'focus') + + document.addEventListener('focusin', focusInListener) + + const focusInEvent = createEvent('focusin', { bubbles: true }) + Object.defineProperty(focusInEvent, 'target', { + value: document.getElementById('outside') + }) + + document.dispatchEvent(focusInEvent) + }) + }) + }) + + describe('deactivate', () => { + it('should flag itself as no longer active', () => { + const focustrap = new FocusTrap({ trapElement: fixtureEl }) + focustrap.activate() + expect(focustrap._isActive).toBeTrue() + + focustrap.deactivate() + expect(focustrap._isActive).toBeFalse() + }) + + it('should remove all event listeners', () => { + const focustrap = new FocusTrap({ trapElement: fixtureEl }) + focustrap.activate() + + const spy = spyOn(EventHandler, 'off') + focustrap.deactivate() + + expect(spy).toHaveBeenCalled() + }) + + it('doesn\'t try removing event listeners unless it needs to (in case it hasn\'t been activated)', () => { + const focustrap = new FocusTrap({ trapElement: fixtureEl }) + + const spy = spyOn(EventHandler, 'off') + focustrap.deactivate() + + expect(spy).not.toHaveBeenCalled() + }) + }) +}) diff --git a/js/tests/unit/util/index.spec.js b/js/tests/unit/util/index.spec.js new file mode 100644 index 0000000..9f28ce0 --- /dev/null +++ b/js/tests/unit/util/index.spec.js @@ -0,0 +1,814 @@ +import * as Util from '../../../src/util/index' +import { clearFixture, getFixture } from '../../helpers/fixture' +import { noop } from '../../../src/util/index' + +describe('Util', () => { + let fixtureEl + + beforeAll(() => { + fixtureEl = getFixture() + }) + + afterEach(() => { + clearFixture() + }) + + describe('getUID', () => { + it('should generate uid', () => { + const uid = Util.getUID('bs') + const uid2 = Util.getUID('bs') + + expect(uid).not.toEqual(uid2) + }) + }) + + describe('getSelectorFromElement', () => { + it('should get selector from data-bs-target', () => { + fixtureEl.innerHTML = [ + '
', + '
' + ].join('') + + const testEl = fixtureEl.querySelector('#test') + + expect(Util.getSelectorFromElement(testEl)).toEqual('.target') + }) + + it('should get selector from href if no data-bs-target set', () => { + fixtureEl.innerHTML = [ + '', + '
' + ].join('') + + const testEl = fixtureEl.querySelector('#test') + + expect(Util.getSelectorFromElement(testEl)).toEqual('.target') + }) + + it('should get selector from href if data-bs-target equal to #', () => { + fixtureEl.innerHTML = [ + '', + '
' + ].join('') + + const testEl = fixtureEl.querySelector('#test') + + expect(Util.getSelectorFromElement(testEl)).toEqual('.target') + }) + + it('should return null if a selector from a href is a url without an anchor', () => { + fixtureEl.innerHTML = [ + '', + '
' + ].join('') + + const testEl = fixtureEl.querySelector('#test') + + expect(Util.getSelectorFromElement(testEl)).toBeNull() + }) + + it('should return the anchor if a selector from a href is a url', () => { + fixtureEl.innerHTML = [ + '', + '
' + ].join('') + + const testEl = fixtureEl.querySelector('#test') + + expect(Util.getSelectorFromElement(testEl)).toEqual('#target') + }) + + it('should return null if selector not found', () => { + fixtureEl.innerHTML = '' + + const testEl = fixtureEl.querySelector('#test') + + expect(Util.getSelectorFromElement(testEl)).toBeNull() + }) + + it('should return null if no selector', () => { + fixtureEl.innerHTML = '
' + + const testEl = fixtureEl.querySelector('div') + + expect(Util.getSelectorFromElement(testEl)).toBeNull() + }) + }) + + describe('getElementFromSelector', () => { + it('should get element from data-bs-target', () => { + fixtureEl.innerHTML = [ + '
', + '
' + ].join('') + + const testEl = fixtureEl.querySelector('#test') + + expect(Util.getElementFromSelector(testEl)).toEqual(fixtureEl.querySelector('.target')) + }) + + it('should get element from href if no data-bs-target set', () => { + fixtureEl.innerHTML = [ + '', + '
' + ].join('') + + const testEl = fixtureEl.querySelector('#test') + + expect(Util.getElementFromSelector(testEl)).toEqual(fixtureEl.querySelector('.target')) + }) + + it('should return null if element not found', () => { + fixtureEl.innerHTML = '' + + const testEl = fixtureEl.querySelector('#test') + + expect(Util.getElementFromSelector(testEl)).toBeNull() + }) + + it('should return null if no selector', () => { + fixtureEl.innerHTML = '
' + + const testEl = fixtureEl.querySelector('div') + + expect(Util.getElementFromSelector(testEl)).toBeNull() + }) + }) + + describe('getTransitionDurationFromElement', () => { + it('should get transition from element', () => { + fixtureEl.innerHTML = '
' + + expect(Util.getTransitionDurationFromElement(fixtureEl.querySelector('div'))).toEqual(300) + }) + + it('should return 0 if the element is undefined or null', () => { + expect(Util.getTransitionDurationFromElement(null)).toEqual(0) + expect(Util.getTransitionDurationFromElement(undefined)).toEqual(0) + }) + + it('should return 0 if the element do not possess transition', () => { + fixtureEl.innerHTML = '
' + + expect(Util.getTransitionDurationFromElement(fixtureEl.querySelector('div'))).toEqual(0) + }) + }) + + describe('triggerTransitionEnd', () => { + it('should trigger transitionend event', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = '
' + + const el = fixtureEl.querySelector('div') + const spy = spyOn(el, 'dispatchEvent').and.callThrough() + + el.addEventListener('transitionend', () => { + expect(spy).toHaveBeenCalled() + resolve() + }) + + Util.triggerTransitionEnd(el) + }) + }) + }) + + describe('isElement', () => { + it('should detect if the parameter is an element or not and return Boolean', () => { + fixtureEl.innerHTML = [ + '
', + '
' + ].join('') + + const el = fixtureEl.querySelector('#foo') + + expect(Util.isElement(el)).toBeTrue() + expect(Util.isElement({})).toBeFalse() + expect(Util.isElement(fixtureEl.querySelectorAll('.test'))).toBeFalse() + }) + + it('should detect jQuery element', () => { + fixtureEl.innerHTML = '
' + + const el = fixtureEl.querySelector('div') + const fakejQuery = { + 0: el, + jquery: 'foo' + } + + expect(Util.isElement(fakejQuery)).toBeTrue() + }) + }) + + describe('getElement', () => { + it('should try to parse element', () => { + fixtureEl.innerHTML = [ + '
', + '
' + ].join('') + + const el = fixtureEl.querySelector('div') + + expect(Util.getElement(el)).toEqual(el) + expect(Util.getElement('#foo')).toEqual(el) + expect(Util.getElement('#fail')).toBeNull() + expect(Util.getElement({})).toBeNull() + expect(Util.getElement([])).toBeNull() + expect(Util.getElement()).toBeNull() + expect(Util.getElement(null)).toBeNull() + expect(Util.getElement(fixtureEl.querySelectorAll('.test'))).toBeNull() + + const fakejQueryObject = { + 0: el, + jquery: 'foo' + } + + expect(Util.getElement(fakejQueryObject)).toEqual(el) + }) + }) + + describe('isVisible', () => { + it('should return false if the element is not defined', () => { + expect(Util.isVisible(null)).toBeFalse() + expect(Util.isVisible(undefined)).toBeFalse() + }) + + it('should return false if the element provided is not a dom element', () => { + expect(Util.isVisible({})).toBeFalse() + }) + + it('should return false if the element is not visible with display none', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(Util.isVisible(div)).toBeFalse() + }) + + it('should return false if the element is not visible with visibility hidden', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + expect(Util.isVisible(div)).toBeFalse() + }) + + it('should return false if an ancestor element is display none', () => { + fixtureEl.innerHTML = [ + '
', + '
', + '
', + '
', + '
', + '
', + '
' + ].join('') + + const div = fixtureEl.querySelector('.content') + + expect(Util.isVisible(div)).toBeFalse() + }) + + it('should return false if an ancestor element is visibility hidden', () => { + fixtureEl.innerHTML = [ + '
', + '
', + '
', + '
', + '
', + '
', + '
' + ].join('') + + const div = fixtureEl.querySelector('.content') + + expect(Util.isVisible(div)).toBeFalse() + }) + + it('should return true if an ancestor element is visibility hidden, but reverted', () => { + fixtureEl.innerHTML = [ + '
', + '
', + '
', + '
', + '
', + '
', + '
' + ].join('') + + const div = fixtureEl.querySelector('.content') + + expect(Util.isVisible(div)).toBeTrue() + }) + + it('should return true if the element is visible', () => { + fixtureEl.innerHTML = [ + '
', + '
', + '
' + ].join('') + + const div = fixtureEl.querySelector('#element') + + expect(Util.isVisible(div)).toBeTrue() + }) + + it('should return false if the element is hidden, but not via display or visibility', () => { + fixtureEl.innerHTML = [ + '
', + '
', + '
' + ].join('') + + const div = fixtureEl.querySelector('#element') + + expect(Util.isVisible(div)).toBeFalse() + }) + + it('should return true if its a closed details element', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('#element') + + expect(Util.isVisible(div)).toBeTrue() + }) + + it('should return true if the element is visible inside an open details element', () => { + fixtureEl.innerHTML = [ + '
', + '
', + '
' + ].join('') + + const div = fixtureEl.querySelector('#element') + + expect(Util.isVisible(div)).toBeTrue() + }) + + it('should return true if the element is a visible summary in a closed details element', () => { + fixtureEl.innerHTML = [ + '
', + ' ', + ' ', + ' ', + '
' + ].join('') + + const element1 = fixtureEl.querySelector('#element-1') + const element2 = fixtureEl.querySelector('#element-2') + + expect(Util.isVisible(element1)).toBeTrue() + expect(Util.isVisible(element2)).toBeTrue() + }) + }) + + describe('isDisabled', () => { + it('should return true if the element is not defined', () => { + expect(Util.isDisabled(null)).toBeTrue() + expect(Util.isDisabled(undefined)).toBeTrue() + expect(Util.isDisabled()).toBeTrue() + }) + + it('should return true if the element provided is not a dom element', () => { + expect(Util.isDisabled({})).toBeTrue() + expect(Util.isDisabled('test')).toBeTrue() + }) + + it('should return true if the element has disabled attribute', () => { + fixtureEl.innerHTML = [ + '
', + '
', + '
', + '
', + '
' + ].join('') + + const div = fixtureEl.querySelector('#element') + const div1 = fixtureEl.querySelector('#element1') + const div2 = fixtureEl.querySelector('#element2') + + expect(Util.isDisabled(div)).toBeTrue() + expect(Util.isDisabled(div1)).toBeTrue() + expect(Util.isDisabled(div2)).toBeTrue() + }) + + it('should return false if the element has disabled attribute with "false" value, or doesn\'t have attribute', () => { + fixtureEl.innerHTML = [ + '
', + '
', + '
', + '
' + ].join('') + + const div = fixtureEl.querySelector('#element') + const div1 = fixtureEl.querySelector('#element1') + + expect(Util.isDisabled(div)).toBeFalse() + expect(Util.isDisabled(div1)).toBeFalse() + }) + + it('should return false if the element is not disabled ', () => { + fixtureEl.innerHTML = [ + '
', + ' ', + ' ', + ' ', + '
' + ].join('') + + const el = selector => fixtureEl.querySelector(selector) + + expect(Util.isDisabled(el('#button'))).toBeFalse() + expect(Util.isDisabled(el('#select'))).toBeFalse() + expect(Util.isDisabled(el('#input'))).toBeFalse() + }) + + it('should return true if the element has disabled attribute', () => { + fixtureEl.innerHTML = [ + '
', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + '
' + ].join('') + + const el = selector => fixtureEl.querySelector(selector) + + expect(Util.isDisabled(el('#input'))).toBeTrue() + expect(Util.isDisabled(el('#input1'))).toBeTrue() + expect(Util.isDisabled(el('#button'))).toBeTrue() + expect(Util.isDisabled(el('#button1'))).toBeTrue() + expect(Util.isDisabled(el('#button2'))).toBeTrue() + expect(Util.isDisabled(el('#input'))).toBeTrue() + }) + + it('should return true if the element has class "disabled"', () => { + fixtureEl.innerHTML = [ + '
', + '
', + '
' + ].join('') + + const div = fixtureEl.querySelector('#element') + + expect(Util.isDisabled(div)).toBeTrue() + }) + + it('should return true if the element has class "disabled" but disabled attribute is false', () => { + fixtureEl.innerHTML = [ + '
', + ' ', + '
' + ].join('') + + const div = fixtureEl.querySelector('#input') + + expect(Util.isDisabled(div)).toBeTrue() + }) + }) + + describe('findShadowRoot', () => { + it('should return null if shadow dom is not available', () => { + // Only for newer browsers + if (!document.documentElement.attachShadow) { + expect().nothing() + return + } + + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + + spyOn(document.documentElement, 'attachShadow').and.returnValue(null) + + expect(Util.findShadowRoot(div)).toBeNull() + }) + + it('should return null when we do not find a shadow root', () => { + // Only for newer browsers + if (!document.documentElement.attachShadow) { + expect().nothing() + return + } + + spyOn(document, 'getRootNode').and.returnValue(undefined) + + expect(Util.findShadowRoot(document)).toBeNull() + }) + + it('should return the shadow root when found', () => { + // Only for newer browsers + if (!document.documentElement.attachShadow) { + expect().nothing() + return + } + + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const shadowRoot = div.attachShadow({ + mode: 'open' + }) + + expect(Util.findShadowRoot(shadowRoot)).toEqual(shadowRoot) + + shadowRoot.innerHTML = '' + + expect(Util.findShadowRoot(shadowRoot.firstChild)).toEqual(shadowRoot) + }) + }) + + describe('noop', () => { + it('should be a function', () => { + expect(Util.noop).toEqual(jasmine.any(Function)) + }) + }) + + describe('reflow', () => { + it('should return element offset height to force the reflow', () => { + fixtureEl.innerHTML = '
' + + const div = fixtureEl.querySelector('div') + const spy = spyOnProperty(div, 'offsetHeight') + Util.reflow(div) + expect(spy).toHaveBeenCalled() + }) + }) + + describe('getjQuery', () => { + const fakejQuery = { trigger() {} } + + beforeEach(() => { + Object.defineProperty(window, 'jQuery', { + value: fakejQuery, + writable: true + }) + }) + + afterEach(() => { + window.jQuery = undefined + }) + + it('should return jQuery object when present', () => { + expect(Util.getjQuery()).toEqual(fakejQuery) + }) + + it('should not return jQuery object when present if data-bs-no-jquery', () => { + document.body.setAttribute('data-bs-no-jquery', '') + + expect(window.jQuery).toEqual(fakejQuery) + expect(Util.getjQuery()).toBeNull() + + document.body.removeAttribute('data-bs-no-jquery') + }) + + it('should not return jQuery if not present', () => { + window.jQuery = undefined + expect(Util.getjQuery()).toBeNull() + }) + }) + + describe('onDOMContentLoaded', () => { + it('should execute callbacks when DOMContentLoaded is fired and should not add more than one listener', () => { + const spy = jasmine.createSpy() + const spy2 = jasmine.createSpy() + + const spyAdd = spyOn(document, 'addEventListener').and.callThrough() + spyOnProperty(document, 'readyState').and.returnValue('loading') + + Util.onDOMContentLoaded(spy) + Util.onDOMContentLoaded(spy2) + + document.dispatchEvent(new Event('DOMContentLoaded', { + bubbles: true, + cancelable: true + })) + + expect(spy).toHaveBeenCalled() + expect(spy2).toHaveBeenCalled() + expect(spyAdd).toHaveBeenCalledTimes(1) + }) + + it('should execute callback if readyState is not "loading"', () => { + const spy = jasmine.createSpy() + Util.onDOMContentLoaded(spy) + expect(spy).toHaveBeenCalled() + }) + }) + + describe('defineJQueryPlugin', () => { + const fakejQuery = { fn: {} } + + beforeEach(() => { + Object.defineProperty(window, 'jQuery', { + value: fakejQuery, + writable: true + }) + }) + + afterEach(() => { + window.jQuery = undefined + }) + + it('should define a plugin on the jQuery instance', () => { + const pluginMock = Util.noop + pluginMock.NAME = 'test' + pluginMock.jQueryInterface = Util.noop + + Util.defineJQueryPlugin(pluginMock) + expect(fakejQuery.fn.test).toEqual(pluginMock.jQueryInterface) + expect(fakejQuery.fn.test.Constructor).toEqual(pluginMock) + expect(fakejQuery.fn.test.noConflict).toEqual(jasmine.any(Function)) + }) + }) + + describe('execute', () => { + it('should execute if arg is function', () => { + const spy = jasmine.createSpy('spy') + Util.execute(spy) + expect(spy).toHaveBeenCalled() + }) + }) + + describe('executeAfterTransition', () => { + it('should immediately execute a function when waitForTransition parameter is false', () => { + const el = document.createElement('div') + const callbackSpy = jasmine.createSpy('callback spy') + const eventListenerSpy = spyOn(el, 'addEventListener') + + Util.executeAfterTransition(callbackSpy, el, false) + + expect(callbackSpy).toHaveBeenCalled() + expect(eventListenerSpy).not.toHaveBeenCalled() + }) + + it('should execute a function when a transitionend event is dispatched', () => { + const el = document.createElement('div') + const callbackSpy = jasmine.createSpy('callback spy') + + spyOn(window, 'getComputedStyle').and.returnValue({ + transitionDuration: '0.05s', + transitionDelay: '0s' + }) + + Util.executeAfterTransition(callbackSpy, el) + + el.dispatchEvent(new TransitionEvent('transitionend')) + + expect(callbackSpy).toHaveBeenCalled() + }) + + it('should execute a function after a computed CSS transition duration and there was no transitionend event dispatched', () => { + return new Promise(resolve => { + const el = document.createElement('div') + const callbackSpy = jasmine.createSpy('callback spy') + + spyOn(window, 'getComputedStyle').and.returnValue({ + transitionDuration: '0.05s', + transitionDelay: '0s' + }) + + Util.executeAfterTransition(callbackSpy, el) + + setTimeout(() => { + expect(callbackSpy).toHaveBeenCalled() + resolve() + }, 70) + }) + }) + + it('should not execute a function a second time after a computed CSS transition duration and if a transitionend event has already been dispatched', () => { + return new Promise(resolve => { + const el = document.createElement('div') + const callbackSpy = jasmine.createSpy('callback spy') + + spyOn(window, 'getComputedStyle').and.returnValue({ + transitionDuration: '0.05s', + transitionDelay: '0s' + }) + + Util.executeAfterTransition(callbackSpy, el) + + setTimeout(() => { + el.dispatchEvent(new TransitionEvent('transitionend')) + }, 50) + + setTimeout(() => { + expect(callbackSpy).toHaveBeenCalledTimes(1) + resolve() + }, 70) + }) + }) + + it('should not trigger a transitionend event if another transitionend event had already happened', () => { + return new Promise(resolve => { + const el = document.createElement('div') + + spyOn(window, 'getComputedStyle').and.returnValue({ + transitionDuration: '0.05s', + transitionDelay: '0s' + }) + + Util.executeAfterTransition(noop, el) + + // simulate a event dispatched by the browser + el.dispatchEvent(new TransitionEvent('transitionend')) + + const dispatchSpy = spyOn(el, 'dispatchEvent').and.callThrough() + + setTimeout(() => { + // setTimeout should not have triggered another transitionend event. + expect(dispatchSpy).not.toHaveBeenCalled() + resolve() + }, 70) + }) + }) + + it('should ignore transitionend events from nested elements', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '
', + '
', + '
' + ].join('') + + const outer = fixtureEl.querySelector('.outer') + const nested = fixtureEl.querySelector('.nested') + const callbackSpy = jasmine.createSpy('callback spy') + + spyOn(window, 'getComputedStyle').and.returnValue({ + transitionDuration: '0.05s', + transitionDelay: '0s' + }) + + Util.executeAfterTransition(callbackSpy, outer) + + nested.dispatchEvent(new TransitionEvent('transitionend', { + bubbles: true + })) + + setTimeout(() => { + expect(callbackSpy).not.toHaveBeenCalled() + }, 20) + + setTimeout(() => { + expect(callbackSpy).toHaveBeenCalled() + resolve() + }, 70) + }) + }) + }) + + describe('getNextActiveElement', () => { + it('should return first element if active not exists or not given and shouldGetNext is either true, or false with cycling being disabled', () => { + const array = ['a', 'b', 'c', 'd'] + + expect(Util.getNextActiveElement(array, '', true, true)).toEqual('a') + expect(Util.getNextActiveElement(array, 'g', true, true)).toEqual('a') + expect(Util.getNextActiveElement(array, '', true, false)).toEqual('a') + expect(Util.getNextActiveElement(array, 'g', true, false)).toEqual('a') + expect(Util.getNextActiveElement(array, '', false, false)).toEqual('a') + expect(Util.getNextActiveElement(array, 'g', false, false)).toEqual('a') + }) + + it('should return last element if active not exists or not given and shouldGetNext is false but cycling is enabled', () => { + const array = ['a', 'b', 'c', 'd'] + + expect(Util.getNextActiveElement(array, '', false, true)).toEqual('d') + expect(Util.getNextActiveElement(array, 'g', false, true)).toEqual('d') + }) + + it('should return next element or same if is last', () => { + const array = ['a', 'b', 'c', 'd'] + + expect(Util.getNextActiveElement(array, 'a', true, true)).toEqual('b') + expect(Util.getNextActiveElement(array, 'b', true, true)).toEqual('c') + expect(Util.getNextActiveElement(array, 'd', true, false)).toEqual('d') + }) + + it('should return next element or first, if is last and "isCycleAllowed = true"', () => { + const array = ['a', 'b', 'c', 'd'] + + expect(Util.getNextActiveElement(array, 'c', true, true)).toEqual('d') + expect(Util.getNextActiveElement(array, 'd', true, true)).toEqual('a') + }) + + it('should return previous element or same if is first', () => { + const array = ['a', 'b', 'c', 'd'] + + expect(Util.getNextActiveElement(array, 'b', false, true)).toEqual('a') + expect(Util.getNextActiveElement(array, 'd', false, true)).toEqual('c') + expect(Util.getNextActiveElement(array, 'a', false, false)).toEqual('a') + }) + + it('should return next element or first, if is last and "isCycleAllowed = true"', () => { + const array = ['a', 'b', 'c', 'd'] + + expect(Util.getNextActiveElement(array, 'd', false, true)).toEqual('c') + expect(Util.getNextActiveElement(array, 'a', false, true)).toEqual('d') + }) + }) +}) diff --git a/js/tests/unit/util/sanitizer.spec.js b/js/tests/unit/util/sanitizer.spec.js new file mode 100644 index 0000000..c656aed --- /dev/null +++ b/js/tests/unit/util/sanitizer.spec.js @@ -0,0 +1,105 @@ +import { DefaultAllowlist, sanitizeHtml } from '../../../src/util/sanitizer' + +describe('Sanitizer', () => { + describe('sanitizeHtml', () => { + it('should return the same on empty string', () => { + const empty = '' + + const result = sanitizeHtml(empty, DefaultAllowlist, null) + + expect(result).toEqual(empty) + }) + + it('should sanitize template by removing tags with XSS', () => { + const template = [ + '
', + ' Click me', + ' Some content', + '
' + ].join('') + + const result = sanitizeHtml(template, DefaultAllowlist, null) + + expect(result).not.toContain('href="javascript:alert(7)') + }) + + it('should sanitize template and work with multiple regex', () => { + const template = [ + '
', + ' Click me', + ' Some content', + '
' + ].join('') + + const myDefaultAllowList = DefaultAllowlist + // With the default allow list + let result = sanitizeHtml(template, myDefaultAllowList, null) + + // `data-foo` won't be present + expect(result).not.toContain('data-foo="bar"') + + // Add the following regex too + myDefaultAllowList['*'].push(/^data-foo/) + + result = sanitizeHtml(template, myDefaultAllowList, null) + + expect(result).not.toContain('href="javascript:alert(7)') // This is in the default list + expect(result).toContain('aria-label="This is a link"') // This is in the default list + expect(result).toContain('data-foo="bar"') // We explicitly allow this + }) + + it('should allow aria attributes and safe attributes', () => { + const template = [ + '
', + ' Some content', + '
' + ].join('') + + const result = sanitizeHtml(template, DefaultAllowlist, null) + + expect(result).toContain('aria-pressed') + expect(result).toContain('class="test"') + }) + + it('should remove tags not in allowlist', () => { + const template = [ + '
', + ' ', + '
' + ].join('') + + const result = sanitizeHtml(template, DefaultAllowlist, null) + + expect(result).not.toContain(' + + diff --git a/js/tests/visual/button.html b/js/tests/visual/button.html new file mode 100644 index 0000000..0c54934 --- /dev/null +++ b/js/tests/visual/button.html @@ -0,0 +1,49 @@ + + + + + + + Button + + +
+

Button Bootstrap Visual Test

+ + + +

For checkboxes and radio buttons, ensure that keyboard behavior is functioning correctly.

+

Navigate to the checkboxes with the keyboard (generally, using TAB / SHIFT + TAB), and ensure that SPACE toggles the currently focused checkbox. Click on one of the checkboxes using the mouse, ensure that focus was correctly set on the actual checkbox, and that SPACE toggles the checkbox again.

+ +
+ + + +
+ +

Navigate to the radio button group with the keyboard (generally, using TAB / SHIFT + TAB). If no radio button was initially set to be selected, the first/last radio button should receive focus (depending on whether you navigated "forward" to the group with TAB or "backwards" using SHIFT + TAB). If a radio button was already selected, navigating with the keyboard should set focus to that particular radio button. Only one radio button in a group should receive focus at any given time. Ensure that the selected radio button can be changed by using the and arrow keys. Click on one of the radio buttons with the mouse, ensure that focus was correctly set on the actual radio button, and that and change the selected radio button again.

+ +
+ + + +
+
+ + + + diff --git a/js/tests/visual/carousel.html b/js/tests/visual/carousel.html new file mode 100644 index 0000000..153c866 --- /dev/null +++ b/js/tests/visual/carousel.html @@ -0,0 +1,65 @@ + + + + + + + Carousel + + + +
+

Carousel Bootstrap Visual Test

+ +

The transition duration should be around 2s. Also, the carousel shouldn't slide when its window/tab is hidden. Check the console log.

+ + +
+ + + + + diff --git a/js/tests/visual/collapse.html b/js/tests/visual/collapse.html new file mode 100644 index 0000000..2782c56 --- /dev/null +++ b/js/tests/visual/collapse.html @@ -0,0 +1,76 @@ + + + + + + + Collapse + + +
+

Collapse Bootstrap Visual Test

+ +
+ + + + +
+
+ + + + diff --git a/js/tests/visual/dropdown.html b/js/tests/visual/dropdown.html new file mode 100644 index 0000000..04cf06d --- /dev/null +++ b/js/tests/visual/dropdown.html @@ -0,0 +1,205 @@ + + + + + + + Dropdown + + +
+

Dropdown Bootstrap Visual Test

+ + + + + +
+
+ +
+ + + +
+
+ +
+ + +
+ + +
+
+ +
+
+ Dropup split align end + + +
+
+ + +
+
+ +
+
+ Dropend split + + +
+
+ + +
+ +
+ Dropstart split + + +
+
+ + +
+
+
+ +
+
+ +
+
+ +
+
+
+ + + + diff --git a/js/tests/visual/modal.html b/js/tests/visual/modal.html new file mode 100644 index 0000000..b738d9e --- /dev/null +++ b/js/tests/visual/modal.html @@ -0,0 +1,275 @@ + + + + + + + Modal + + + + + +
+

Modal Bootstrap Visual Test

+ + + + + + + + + + + +

+ + + (See Issue #18365) + +

+ + + +

+ + + + + +

+ + +
+ + + + + diff --git a/js/tests/visual/popover.html b/js/tests/visual/popover.html new file mode 100644 index 0000000..73edf99 --- /dev/null +++ b/js/tests/visual/popover.html @@ -0,0 +1,41 @@ + + + + + + + Popover + + +
+

Popover Bootstrap Visual Test

+ + + + + + + + + + +
+ + + + + diff --git a/js/tests/visual/scrollspy.html b/js/tests/visual/scrollspy.html new file mode 100644 index 0000000..2daa7ab --- /dev/null +++ b/js/tests/visual/scrollspy.html @@ -0,0 +1,91 @@ + + + + + + + Scrollspy + + + + +
+

@fat

+

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

+

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

+

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

+

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

+

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

+
+

@mdo

+

Veniam marfa mustache skateboard, adipisicing fugiat velit pitchfork beard. Freegan beard aliqua cupidatat mcsweeney's vero. Cupidatat four loko nisi, ea helvetica nulla carles. Tattooed cosby sweater food truck, mcsweeney's quis non freegan vinyl. Lo-fi wes anderson +1 sartorial. Carles non aesthetic exercitation quis gentrify. Brooklyn adipisicing craft beer vice keytar deserunt.

+

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

+

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

+

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

+

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

+
+

one

+

Occaecat commodo aliqua delectus. Fap craft beer deserunt skateboard ea. Lomo bicycle rights adipisicing banh mi, velit ea sunt next level locavore single-origin coffee in magna veniam. High life id vinyl, echo park consequat quis aliquip banh mi pitchfork. Vero VHS est adipisicing. Consectetur nisi DIY minim messenger bag. Cred ex in, sustainable delectus consectetur fanny pack iphone.

+

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

+

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

+

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

+

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

+
+

two

+

In incididunt echo park, officia deserunt mcsweeney's proident master cleanse thundercats sapiente veniam. Excepteur VHS elit, proident shoreditch +1 biodiesel laborum craft beer. Single-origin coffee wayfarers irure four loko, cupidatat terry richardson master cleanse. Assumenda you probably haven't heard of them art party fanny pack, tattooed nulla cardigan tempor ad. Proident wolf nesciunt sartorial keffiyeh eu banh mi sustainable. Elit wolf voluptate, lo-fi ea portland before they sold out four loko. Locavore enim nostrud mlkshk brooklyn nesciunt.

+

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

+

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

+

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

+

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

+
+

three

+

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

+

Keytar twee blog, culpa messenger bag marfa whatever delectus food truck. Sapiente synth id assumenda. Locavore sed helvetica cliche irony, thundercats you probably haven't heard of them consequat hoodie gluten-free lo-fi fap aliquip. Labore elit placeat before they sold out, terry richardson proident brunch nesciunt quis cosby sweater pariatur keffiyeh ut helvetica artisan. Cardigan craft beer seitan readymade velit. VHS chambray laboris tempor veniam. Anim mollit minim commodo ullamco thundercats.

+

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

+

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

+

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

+

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

+

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

+

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

+

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

+

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

+

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

+

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

+

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

+

Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.

+
+

Final section

+

Ad leggings keytar, brunch id art party dolor labore.

+
+ + + + diff --git a/js/tests/visual/tab.html b/js/tests/visual/tab.html new file mode 100644 index 0000000..4cbc86c --- /dev/null +++ b/js/tests/visual/tab.html @@ -0,0 +1,223 @@ + + + + + + + Tab + + + +
+

Tab Bootstrap Visual Test

+ +

Tabs without fade

+ + + +
+
+

Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica. Reprehenderit butcher retro keffiyeh dreamcatcher synth. Cosby sweater eu banh mi, qui irure terry richardson ex squid. Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui.

+

Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica. Reprehenderit butcher retro keffiyeh dreamcatcher synth. Cosby sweater eu banh mi, qui irure terry richardson ex squid. Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui.

+
+
+

Food truck fixie locavore, accusamus mcsweeney's marfa nulla single-origin coffee squid. Exercitation +1 labore velit, blog sartorial PBR leggings next level wes anderson artisan four loko farm-to-table craft beer twee. Qui photo booth letterpress, commodo enim craft beer mlkshk aliquip jean shorts ullamco ad vinyl cillum PBR. Homo nostrud organic, assumenda labore aesthetic magna delectus mollit. Keytar helvetica VHS salvia yr, vero magna velit sapiente labore stumptown. Vegan fanny pack odio cillum wes anderson 8-bit, sustainable jean shorts beard ut DIY ethical culpa terry richardson biodiesel. Art party scenester stumptown, tumblr butcher vero sint qui sapiente accusamus tattooed echo park.

+

Food truck fixie locavore, accusamus mcsweeney's marfa nulla single-origin coffee squid. Exercitation +1 labore velit, blog sartorial PBR leggings next level wes anderson artisan four loko farm-to-table craft beer twee. Qui photo booth letterpress, commodo enim craft beer mlkshk aliquip jean shorts ullamco ad vinyl cillum PBR. Homo nostrud organic, assumenda labore aesthetic magna delectus mollit. Keytar helvetica VHS salvia yr, vero magna velit sapiente labore stumptown. Vegan fanny pack odio cillum wes anderson 8-bit, sustainable jean shorts beard ut DIY ethical culpa terry richardson biodiesel. Art party scenester stumptown, tumblr butcher vero sint qui sapiente accusamus tattooed echo park.

+
+
+

Etsy mixtape wayfarers, ethical wes anderson tofu before they sold out mcsweeney's organic lomo retro fanny pack lo-fi farm-to-table readymade. Messenger bag gentrify pitchfork tattooed craft beer, iphone skateboard locavore carles etsy salvia banksy hoodie helvetica. DIY synth PBR banksy irony. Leggings gentrify squid 8-bit cred pitchfork. Williamsburg banh mi whatever gluten-free, carles pitchfork biodiesel fixie etsy retro mlkshk vice blog. Scenester cred you probably haven't heard of them, vinyl craft beer blog stumptown. Pitchfork sustainable tofu synth chambray yr.

+

Etsy mixtape wayfarers, ethical wes anderson tofu before they sold out mcsweeney's organic lomo retro fanny pack lo-fi farm-to-table readymade. Messenger bag gentrify pitchfork tattooed craft beer, iphone skateboard locavore carles etsy salvia banksy hoodie helvetica. DIY synth PBR banksy irony. Leggings gentrify squid 8-bit cred pitchfork. Williamsburg banh mi whatever gluten-free, carles pitchfork biodiesel fixie etsy retro mlkshk vice blog. Scenester cred you probably haven't heard of them, vinyl craft beer blog stumptown. Pitchfork sustainable tofu synth chambray yr.

+
+
+

Trust fund seitan letterpress, keytar raw denim keffiyeh etsy art party before they sold out master cleanse gluten-free squid scenester freegan cosby sweater. Fanny pack portland seitan DIY, art party locavore wolf cliche high life echo park Austin. Cred vinyl keffiyeh DIY salvia PBR, banh mi before they sold out farm-to-table VHS viral locavore cosby sweater. Lomo wolf viral, mustache readymade thundercats keffiyeh craft beer marfa ethical. Wolf salvia freegan, sartorial keffiyeh echo park vegan.

+

Trust fund seitan letterpress, keytar raw denim keffiyeh etsy art party before they sold out master cleanse gluten-free squid scenester freegan cosby sweater. Fanny pack portland seitan DIY, art party locavore wolf cliche high life echo park Austin. Cred vinyl keffiyeh DIY salvia PBR, banh mi before they sold out farm-to-table VHS viral locavore cosby sweater. Lomo wolf viral, mustache readymade thundercats keffiyeh craft beer marfa ethical. Wolf salvia freegan, sartorial keffiyeh echo park vegan.

+
+
+ +

Tabs with fade

+ + + +
+
+

Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica. Reprehenderit butcher retro keffiyeh dreamcatcher synth. Cosby sweater eu banh mi, qui irure terry richardson ex squid. Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui.

+

Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica. Reprehenderit butcher retro keffiyeh dreamcatcher synth. Cosby sweater eu banh mi, qui irure terry richardson ex squid. Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui.

+
+
+

Food truck fixie locavore, accusamus mcsweeney's marfa nulla single-origin coffee squid. Exercitation +1 labore velit, blog sartorial PBR leggings next level wes anderson artisan four loko farm-to-table craft beer twee. Qui photo booth letterpress, commodo enim craft beer mlkshk aliquip jean shorts ullamco ad vinyl cillum PBR. Homo nostrud organic, assumenda labore aesthetic magna delectus mollit. Keytar helvetica VHS salvia yr, vero magna velit sapiente labore stumptown. Vegan fanny pack odio cillum wes anderson 8-bit, sustainable jean shorts beard ut DIY ethical culpa terry richardson biodiesel. Art party scenester stumptown, tumblr butcher vero sint qui sapiente accusamus tattooed echo park.

+

Food truck fixie locavore, accusamus mcsweeney's marfa nulla single-origin coffee squid. Exercitation +1 labore velit, blog sartorial PBR leggings next level wes anderson artisan four loko farm-to-table craft beer twee. Qui photo booth letterpress, commodo enim craft beer mlkshk aliquip jean shorts ullamco ad vinyl cillum PBR. Homo nostrud organic, assumenda labore aesthetic magna delectus mollit. Keytar helvetica VHS salvia yr, vero magna velit sapiente labore stumptown. Vegan fanny pack odio cillum wes anderson 8-bit, sustainable jean shorts beard ut DIY ethical culpa terry richardson biodiesel. Art party scenester stumptown, tumblr butcher vero sint qui sapiente accusamus tattooed echo park.

+
+
+

Etsy mixtape wayfarers, ethical wes anderson tofu before they sold out mcsweeney's organic lomo retro fanny pack lo-fi farm-to-table readymade. Messenger bag gentrify pitchfork tattooed craft beer, iphone skateboard locavore carles etsy salvia banksy hoodie helvetica. DIY synth PBR banksy irony. Leggings gentrify squid 8-bit cred pitchfork. Williamsburg banh mi whatever gluten-free, carles pitchfork biodiesel fixie etsy retro mlkshk vice blog. Scenester cred you probably haven't heard of them, vinyl craft beer blog stumptown. Pitchfork sustainable tofu synth chambray yr.

+

Etsy mixtape wayfarers, ethical wes anderson tofu before they sold out mcsweeney's organic lomo retro fanny pack lo-fi farm-to-table readymade. Messenger bag gentrify pitchfork tattooed craft beer, iphone skateboard locavore carles etsy salvia banksy hoodie helvetica. DIY synth PBR banksy irony. Leggings gentrify squid 8-bit cred pitchfork. Williamsburg banh mi whatever gluten-free, carles pitchfork biodiesel fixie etsy retro mlkshk vice blog. Scenester cred you probably haven't heard of them, vinyl craft beer blog stumptown. Pitchfork sustainable tofu synth chambray yr.

+
+
+

Trust fund seitan letterpress, keytar raw denim keffiyeh etsy art party before they sold out master cleanse gluten-free squid scenester freegan cosby sweater. Fanny pack portland seitan DIY, art party locavore wolf cliche high life echo park Austin. Cred vinyl keffiyeh DIY salvia PBR, banh mi before they sold out farm-to-table VHS viral locavore cosby sweater. Lomo wolf viral, mustache readymade thundercats keffiyeh craft beer marfa ethical. Wolf salvia freegan, sartorial keffiyeh echo park vegan.

+

Trust fund seitan letterpress, keytar raw denim keffiyeh etsy art party before they sold out master cleanse gluten-free squid scenester freegan cosby sweater. Fanny pack portland seitan DIY, art party locavore wolf cliche high life echo park Austin. Cred vinyl keffiyeh DIY salvia PBR, banh mi before they sold out farm-to-table VHS viral locavore cosby sweater. Lomo wolf viral, mustache readymade thundercats keffiyeh craft beer marfa ethical. Wolf salvia freegan, sartorial keffiyeh echo park vegan.

+
+
+ +

Tabs without fade (no initially active pane)

+ + + +
+
+

Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica. Reprehenderit butcher retro keffiyeh dreamcatcher synth. Cosby sweater eu banh mi, qui irure terry richardson ex squid. Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui.

+

Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica. Reprehenderit butcher retro keffiyeh dreamcatcher synth. Cosby sweater eu banh mi, qui irure terry richardson ex squid. Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui.

+
+
+

Food truck fixie locavore, accusamus mcsweeney's marfa nulla single-origin coffee squid. Exercitation +1 labore velit, blog sartorial PBR leggings next level wes anderson artisan four loko farm-to-table craft beer twee. Qui photo booth letterpress, commodo enim craft beer mlkshk aliquip jean shorts ullamco ad vinyl cillum PBR. Homo nostrud organic, assumenda labore aesthetic magna delectus mollit. Keytar helvetica VHS salvia yr, vero magna velit sapiente labore stumptown. Vegan fanny pack odio cillum wes anderson 8-bit, sustainable jean shorts beard ut DIY ethical culpa terry richardson biodiesel. Art party scenester stumptown, tumblr butcher vero sint qui sapiente accusamus tattooed echo park.

+

Food truck fixie locavore, accusamus mcsweeney's marfa nulla single-origin coffee squid. Exercitation +1 labore velit, blog sartorial PBR leggings next level wes anderson artisan four loko farm-to-table craft beer twee. Qui photo booth letterpress, commodo enim craft beer mlkshk aliquip jean shorts ullamco ad vinyl cillum PBR. Homo nostrud organic, assumenda labore aesthetic magna delectus mollit. Keytar helvetica VHS salvia yr, vero magna velit sapiente labore stumptown. Vegan fanny pack odio cillum wes anderson 8-bit, sustainable jean shorts beard ut DIY ethical culpa terry richardson biodiesel. Art party scenester stumptown, tumblr butcher vero sint qui sapiente accusamus tattooed echo park.

+
+
+

Etsy mixtape wayfarers, ethical wes anderson tofu before they sold out mcsweeney's organic lomo retro fanny pack lo-fi farm-to-table readymade. Messenger bag gentrify pitchfork tattooed craft beer, iphone skateboard locavore carles etsy salvia banksy hoodie helvetica. DIY synth PBR banksy irony. Leggings gentrify squid 8-bit cred pitchfork. Williamsburg banh mi whatever gluten-free, carles pitchfork biodiesel fixie etsy retro mlkshk vice blog. Scenester cred you probably haven't heard of them, vinyl craft beer blog stumptown. Pitchfork sustainable tofu synth chambray yr.

+

Etsy mixtape wayfarers, ethical wes anderson tofu before they sold out mcsweeney's organic lomo retro fanny pack lo-fi farm-to-table readymade. Messenger bag gentrify pitchfork tattooed craft beer, iphone skateboard locavore carles etsy salvia banksy hoodie helvetica. DIY synth PBR banksy irony. Leggings gentrify squid 8-bit cred pitchfork. Williamsburg banh mi whatever gluten-free, carles pitchfork biodiesel fixie etsy retro mlkshk vice blog. Scenester cred you probably haven't heard of them, vinyl craft beer blog stumptown. Pitchfork sustainable tofu synth chambray yr.

+
+
+

Trust fund seitan letterpress, keytar raw denim keffiyeh etsy art party before they sold out master cleanse gluten-free squid scenester freegan cosby sweater. Fanny pack portland seitan DIY, art party locavore wolf cliche high life echo park Austin. Cred vinyl keffiyeh DIY salvia PBR, banh mi before they sold out farm-to-table VHS viral locavore cosby sweater. Lomo wolf viral, mustache readymade thundercats keffiyeh craft beer marfa ethical. Wolf salvia freegan, sartorial keffiyeh echo park vegan.

+

Trust fund seitan letterpress, keytar raw denim keffiyeh etsy art party before they sold out master cleanse gluten-free squid scenester freegan cosby sweater. Fanny pack portland seitan DIY, art party locavore wolf cliche high life echo park Austin. Cred vinyl keffiyeh DIY salvia PBR, banh mi before they sold out farm-to-table VHS viral locavore cosby sweater. Lomo wolf viral, mustache readymade thundercats keffiyeh craft beer marfa ethical. Wolf salvia freegan, sartorial keffiyeh echo park vegan.

+
+
+ +

Tabs with fade (no initially active pane)

+ + + +
+
+

Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica. Reprehenderit butcher retro keffiyeh dreamcatcher synth. Cosby sweater eu banh mi, qui irure terry richardson ex squid. Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui.

+

Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica. Reprehenderit butcher retro keffiyeh dreamcatcher synth. Cosby sweater eu banh mi, qui irure terry richardson ex squid. Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui.

+
+
+

Food truck fixie locavore, accusamus mcsweeney's marfa nulla single-origin coffee squid. Exercitation +1 labore velit, blog sartorial PBR leggings next level wes anderson artisan four loko farm-to-table craft beer twee. Qui photo booth letterpress, commodo enim craft beer mlkshk aliquip jean shorts ullamco ad vinyl cillum PBR. Homo nostrud organic, assumenda labore aesthetic magna delectus mollit. Keytar helvetica VHS salvia yr, vero magna velit sapiente labore stumptown. Vegan fanny pack odio cillum wes anderson 8-bit, sustainable jean shorts beard ut DIY ethical culpa terry richardson biodiesel. Art party scenester stumptown, tumblr butcher vero sint qui sapiente accusamus tattooed echo park.

+

Food truck fixie locavore, accusamus mcsweeney's marfa nulla single-origin coffee squid. Exercitation +1 labore velit, blog sartorial PBR leggings next level wes anderson artisan four loko farm-to-table craft beer twee. Qui photo booth letterpress, commodo enim craft beer mlkshk aliquip jean shorts ullamco ad vinyl cillum PBR. Homo nostrud organic, assumenda labore aesthetic magna delectus mollit. Keytar helvetica VHS salvia yr, vero magna velit sapiente labore stumptown. Vegan fanny pack odio cillum wes anderson 8-bit, sustainable jean shorts beard ut DIY ethical culpa terry richardson biodiesel. Art party scenester stumptown, tumblr butcher vero sint qui sapiente accusamus tattooed echo park.

+
+
+

Etsy mixtape wayfarers, ethical wes anderson tofu before they sold out mcsweeney's organic lomo retro fanny pack lo-fi farm-to-table readymade. Messenger bag gentrify pitchfork tattooed craft beer, iphone skateboard locavore carles etsy salvia banksy hoodie helvetica. DIY synth PBR banksy irony. Leggings gentrify squid 8-bit cred pitchfork. Williamsburg banh mi whatever gluten-free, carles pitchfork biodiesel fixie etsy retro mlkshk vice blog. Scenester cred you probably haven't heard of them, vinyl craft beer blog stumptown. Pitchfork sustainable tofu synth chambray yr.

+

Etsy mixtape wayfarers, ethical wes anderson tofu before they sold out mcsweeney's organic lomo retro fanny pack lo-fi farm-to-table readymade. Messenger bag gentrify pitchfork tattooed craft beer, iphone skateboard locavore carles etsy salvia banksy hoodie helvetica. DIY synth PBR banksy irony. Leggings gentrify squid 8-bit cred pitchfork. Williamsburg banh mi whatever gluten-free, carles pitchfork biodiesel fixie etsy retro mlkshk vice blog. Scenester cred you probably haven't heard of them, vinyl craft beer blog stumptown. Pitchfork sustainable tofu synth chambray yr.

+
+
+

Trust fund seitan letterpress, keytar raw denim keffiyeh etsy art party before they sold out master cleanse gluten-free squid scenester freegan cosby sweater. Fanny pack portland seitan DIY, art party locavore wolf cliche high life echo park Austin. Cred vinyl keffiyeh DIY salvia PBR, banh mi before they sold out farm-to-table VHS viral locavore cosby sweater. Lomo wolf viral, mustache readymade thundercats keffiyeh craft beer marfa ethical. Wolf salvia freegan, sartorial keffiyeh echo park vegan.

+

Trust fund seitan letterpress, keytar raw denim keffiyeh etsy art party before they sold out master cleanse gluten-free squid scenester freegan cosby sweater. Fanny pack portland seitan DIY, art party locavore wolf cliche high life echo park Austin. Cred vinyl keffiyeh DIY salvia PBR, banh mi before they sold out farm-to-table VHS viral locavore cosby sweater. Lomo wolf viral, mustache readymade thundercats keffiyeh craft beer marfa ethical. Wolf salvia freegan, sartorial keffiyeh echo park vegan.

+
+
+ +

Tabs with nav and using links (with fade)

+ + +
+
+

Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica. Reprehenderit butcher retro keffiyeh dreamcatcher synth. Cosby sweater eu banh mi, qui irure terry richardson ex squid. Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui.

+

Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica. Reprehenderit butcher retro keffiyeh dreamcatcher synth. Cosby sweater eu banh mi, qui irure terry richardson ex squid. Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui.

+
+
+

Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica. Reprehenderit butcher retro keffiyeh dreamcatcher synth. Cosby sweater eu banh mi, qui irure terry richardson ex squid. Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui.

+

Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica. Reprehenderit butcher retro keffiyeh dreamcatcher synth. Cosby sweater eu banh mi, qui irure terry richardson ex squid. Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui.

+
+
+

Etsy mixtape wayfarers, ethical wes anderson tofu before they sold out mcsweeney's organic lomo retro fanny pack lo-fi farm-to-table readymade. Messenger bag gentrify pitchfork tattooed craft beer, iphone skateboard locavore carles etsy salvia banksy hoodie helvetica. DIY synth PBR banksy irony. Leggings gentrify squid 8-bit cred pitchfork. Williamsburg banh mi whatever gluten-free, carles pitchfork biodiesel fixie etsy retro mlkshk vice blog. Scenester cred you probably haven't heard of them, vinyl craft beer blog stumptown. Pitchfork sustainable tofu synth chambray yr.

+

Etsy mixtape wayfarers, ethical wes anderson tofu before they sold out mcsweeney's organic lomo retro fanny pack lo-fi farm-to-table readymade. Messenger bag gentrify pitchfork tattooed craft beer, iphone skateboard locavore carles etsy salvia banksy hoodie helvetica. DIY synth PBR banksy irony. Leggings gentrify squid 8-bit cred pitchfork. Williamsburg banh mi whatever gluten-free, carles pitchfork biodiesel fixie etsy retro mlkshk vice blog. Scenester cred you probably haven't heard of them, vinyl craft beer blog stumptown. Pitchfork sustainable tofu synth chambray yr.

+
+
+

Trust fund seitan letterpress, keytar raw denim keffiyeh etsy art party before they sold out master cleanse gluten-free squid scenester freegan cosby sweater. Fanny pack portland seitan DIY, art party locavore wolf cliche high life echo park Austin. Cred vinyl keffiyeh DIY salvia PBR, banh mi before they sold out farm-to-table VHS viral locavore cosby sweater. Lomo wolf viral, mustache readymade thundercats keffiyeh craft beer marfa ethical. Wolf salvia freegan, sartorial keffiyeh echo park vegan.

+

Trust fund seitan letterpress, keytar raw denim keffiyeh etsy art party before they sold out master cleanse gluten-free squid scenester freegan cosby sweater. Fanny pack portland seitan DIY, art party locavore wolf cliche high life echo park Austin. Cred vinyl keffiyeh DIY salvia PBR, banh mi before they sold out farm-to-table VHS viral locavore cosby sweater. Lomo wolf viral, mustache readymade thundercats keffiyeh craft beer marfa ethical. Wolf salvia freegan, sartorial keffiyeh echo park vegan.

+
+
+ +

Tabs with list-group (with fade)

+
+
+
+ + + + +
+
+
+ +
+
+
+ + + + diff --git a/js/tests/visual/toast.html b/js/tests/visual/toast.html new file mode 100644 index 0000000..f86926d --- /dev/null +++ b/js/tests/visual/toast.html @@ -0,0 +1,70 @@ + + + + + + + Toast + + + +
+

Toast Bootstrap Visual Test

+ +
+
+ + +
+
+
+ +
+ + + +
+ + + + + diff --git a/js/tests/visual/tooltip.html b/js/tests/visual/tooltip.html new file mode 100644 index 0000000..1a3b9f2 --- /dev/null +++ b/js/tests/visual/tooltip.html @@ -0,0 +1,138 @@ + + + + + + + Tooltip + + + +
+

Tooltip Bootstrap Visual Test

+ +

Tight pants next level keffiyeh you probably haven't heard of them. Photo booth beard raw denim letterpress vegan messenger bag stumptown. Farm-to-table seitan, mcsweeney's fixie sustainable quinoa 8-bit american apparel have a terry richardson vinyl chambray. Beard stumptown, cardigans banh mi lomo thundercats. Tofu biodiesel williamsburg marfa, four loko mcsweeney's cleanse vegan chambray. A really ironic artisan whatever keytar, scenester farm-to-table banksy Austin twitter handle freegan cred raw denim single-origin coffee viral.

+ +
+ +
+

+ + + + + +

+
+
+

+ + + + +

+
+
+
+
+
+
+
+
+ +
+
+
Test Selector triggered tooltips
+
+
+ + +
+ +
+
+ +
+
+
+ + + + + + + + -- cgit v1.2.3