diff --git a/test/DocSearch-test.js b/test/DocSearch-test.js index 7b3a9649..e85e0751 100644 --- a/test/DocSearch-test.js +++ b/test/DocSearch-test.js @@ -4,6 +4,7 @@ import jsdom from 'mocha-jsdom'; import expect from 'expect'; import sinon from 'sinon'; +import {waitForAndRun} from './helpers'; describe('DocSearch', () => { let DocSearch; @@ -330,6 +331,31 @@ describe('DocSearch', () => { }); }); + describe('handleSelected', () => { + it('should change the location', (done) => { + // Given + const options = { + apiKey: 'key', + indexName: 'foo', + inputSelector: '#input' + }; + + // When + let ds = new DocSearch(options); + ds.autocomplete.trigger('autocomplete:selected', {url: 'https://website.com/doc/page'}); + + // Then asynchronously + waitForAndRun(() => { + // escape as soon as the URL has changed + return window.location.href !== 'about:blank'; + }, () => { + // then + expect(window.location.href).toEqual('https://website.com/doc/page'); + done(); + }, 100); + }); + }); + describe('formatHits', () => { it('should not mutate the input', () => { // Given diff --git a/test/helpers.js b/test/helpers.js index 410cb6b7..8a9d16cb 100644 --- a/test/helpers.js +++ b/test/helpers.js @@ -3,3 +3,31 @@ global.ddescribe = describe.only; global.xdescribe = describe.skip; global.iit = it.only; global.xit = it.skip; + +/** + * Wait for max `escapeTime` ms and run `runFunction` except if `escapeFunction` returned true + */ +function waitForAndRun(escapeFunction, runFunction, escapeTime) { + // check the escapeFunction every millisecond so as soon as it is met we can escape the function + var interval = setInterval(function() { + if (escapeFunction()) { + clearMe(); + runFunction(); + } + }, 1); + // in case we never reach the escapeFunction, we will time out + // at the escapeTime + var timeOut = setTimeout(function() { + clearMe(); + runFunction(); + }, escapeTime); + // clear the interval and the timeout + function clearMe() { + clearInterval(interval); + clearTimeout(timeOut); + } +} + +module.exports = { + waitForAndRun +};