search_spec.js 33.6 KB
Newer Older
1 2 3
define([
    'jquery',
    'backbone',
Martyn James committed
4
    'logger',
5
    'common/js/spec_helpers/ajax_helpers',
6
    'common/js/spec_helpers/page_helpers',
7
    'common/js/spec_helpers/template_helpers',
8 9 10 11 12 13 14 15 16
    'js/search/base/models/search_result',
    'js/search/base/collections/search_collection',
    'js/search/base/routers/search_router',
    'js/search/course/views/search_item_view',
    'js/search/dashboard/views/search_item_view',
    'js/search/course/views/search_form',
    'js/search/dashboard/views/search_form',
    'js/search/course/views/search_results_view',
    'js/search/dashboard/views/search_results_view',
cahrens committed
17 18
    'js/search/course/course_search_factory',
    'js/search/dashboard/dashboard_search_factory'
19 20 21
], function(
    $,
    Backbone,
Martyn James committed
22
    Logger,
23
    AjaxHelpers,
24
    PageHelpers,
25 26 27 28
    TemplateHelpers,
    SearchResult,
    SearchCollection,
    SearchRouter,
29 30 31 32 33 34
    CourseSearchItemView,
    DashSearchItemView,
    CourseSearchForm,
    DashSearchForm,
    CourseSearchResultsView,
    DashSearchResultsView,
cahrens committed
35 36
    CourseSearchFactory,
    DashboardSearchFactory
37 38 39
) {
    'use strict';

40
    describe('Search', function() {
41
        beforeEach(function () {
42
            PageHelpers.preventBackboneChangingUrl();
43 44
        });

45
        describe('SearchResult', function () {
46

47 48 49
            beforeEach(function () {
                this.result = new SearchResult();
            });
50

51 52 53 54 55 56
            it('has properties', function () {
                expect(this.result.get('location')).toBeDefined();
                expect(this.result.get('content_type')).toBeDefined();
                expect(this.result.get('excerpt')).toBeDefined();
                expect(this.result.get('url')).toBeDefined();
            });
57 58 59

        });

60

61
        describe('SearchCollection', function () {
62

63 64
            beforeEach(function () {
                this.collection = new SearchCollection();
65

66 67
                this.onSearch = jasmine.createSpy('onSearch');
                this.collection.on('search', this.onSearch);
68

69 70
                this.onNext = jasmine.createSpy('onNext');
                this.collection.on('next', this.onNext);
71

72 73 74
                this.onError = jasmine.createSpy('onError');
                this.collection.on('error', this.onError);
            });
75

76 77 78 79
            it('sends a request without a course ID', function () {
                var collection = new SearchCollection([]);
                spyOn($, 'ajax');
                collection.performSearch('search string');
80
                expect($.ajax.calls.mostRecent().args[0].url).toEqual('/search/');
81
            });
82

83 84 85 86
            it('sends a request with course ID', function () {
                var collection = new SearchCollection([], { courseId: 'edx101' });
                spyOn($, 'ajax');
                collection.performSearch('search string');
87
                expect($.ajax.calls.mostRecent().args[0].url).toEqual('/search/edx101');
88
            });
89

90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
            it('sends a request and parses the json result', function () {
                var requests = AjaxHelpers.requests(this);
                this.collection.performSearch('search string');
                var response = {
                    total: 2,
                    access_denied_count: 1,
                    results: [{
                        data: {
                            location: ['section', 'subsection', 'unit'],
                            url: '/some/url/to/content',
                            content_type: 'text',
                            excerpt: 'this is a short excerpt'
                        }
                    }]
                };
                AjaxHelpers.respondWithJson(requests, response);
106

107 108 109 110 111 112 113
                expect(this.onSearch).toHaveBeenCalled();
                expect(this.collection.totalCount).toEqual(1);
                expect(this.collection.latestModelsCount).toEqual(1);
                expect(this.collection.accessDeniedCount).toEqual(1);
                expect(this.collection.page).toEqual(0);
                expect(this.collection.first().attributes).toEqual(response.results[0].data);
            });
114

115 116 117 118 119 120 121
            it('handles errors', function () {
                var requests = AjaxHelpers.requests(this);
                this.collection.performSearch('search string');
                AjaxHelpers.respondWithError(requests, 500);
                expect(this.onSearch).not.toHaveBeenCalled();
                expect(this.onError).toHaveBeenCalled();
            });
122

123 124 125 126 127 128 129 130
            it('loads next page', function () {
                var requests = AjaxHelpers.requests(this);
                var response = { total: 35, results: [] };
                this.collection.loadNextPage();
                AjaxHelpers.respondWithJson(requests, response);
                expect(this.onNext).toHaveBeenCalled();
                expect(this.onError).not.toHaveBeenCalled();
            });
131

132 133 134 135 136 137 138 139 140 141
            it('sends correct paging parameters', function () {
                var requests = AjaxHelpers.requests(this);
                var searchString = 'search string';
                var response = { total: 52, results: [] };
                this.collection.performSearch(searchString);
                AjaxHelpers.respondWithJson(requests, response);
                this.collection.loadNextPage();
                AjaxHelpers.respondWithJson(requests, response);
                spyOn($, 'ajax');
                this.collection.loadNextPage();
142 143 144 145
                expect($.ajax.calls.mostRecent().args[0].url).toEqual(this.collection.url);
                expect($.ajax.calls.mostRecent().args[0].data.search_string).toEqual(searchString);
                expect($.ajax.calls.mostRecent().args[0].data.page_size).toEqual(this.collection.pageSize);
                expect($.ajax.calls.mostRecent().args[0].data.page_index).toEqual(2);
146 147
            });

148 149 150
            it('has next page', function () {
                var requests = AjaxHelpers.requests(this);
                var response = { total: 35, access_denied_count: 5, results: [] };
151
                this.collection.performSearch('search string');
152 153 154 155 156
                AjaxHelpers.respondWithJson(requests, response);
                expect(this.collection.hasNextPage()).toEqual(true);
                this.collection.loadNextPage();
                AjaxHelpers.respondWithJson(requests, response);
                expect(this.collection.hasNextPage()).toEqual(false);
157 158
            });

159 160 161
            it('aborts any previous request', function () {
                var requests = AjaxHelpers.requests(this);
                var response = { total: 35, results: [] };
162

163 164
                this.collection.performSearch('old search');
                this.collection.performSearch('new search');
165
                AjaxHelpers.skipResetRequest(requests);
166
                AjaxHelpers.respondWithJson(requests, response);
167
                expect(this.onSearch.calls.count()).toEqual(1);
168

169 170
                this.collection.performSearch('old search');
                this.collection.cancelSearch();
171
                AjaxHelpers.skipResetRequest(requests);
172
                expect(this.onSearch.calls.count()).toEqual(1);
173

174 175
                this.collection.loadNextPage();
                this.collection.loadNextPage();
176
                AjaxHelpers.skipResetRequest(requests);
177
                AjaxHelpers.respondWithJson(requests, response);
178
                expect(this.onNext.calls.count()).toEqual(1);
179
            });
180

181
            describe('reset state', function () {
182

183 184 185 186 187
                beforeEach(function () {
                    this.collection.page = 2;
                    this.collection.totalCount = 35;
                    this.collection.latestModelsCount = 5;
                });
188

189 190 191 192 193 194 195
                it('resets state when performing new search', function () {
                    this.collection.performSearch('search string');
                    expect(this.collection.models.length).toEqual(0);
                    expect(this.collection.page).toEqual(0);
                    expect(this.collection.totalCount).toEqual(0);
                    expect(this.collection.latestModelsCount).toEqual(0);
                });
196

197 198 199 200 201 202 203
                it('resets state when canceling a search', function () {
                    this.collection.cancelSearch();
                    expect(this.collection.models.length).toEqual(0);
                    expect(this.collection.page).toEqual(0);
                    expect(this.collection.totalCount).toEqual(0);
                    expect(this.collection.latestModelsCount).toEqual(0);
                });
204

205
            });
206

207
        });
208 209


210
        describe('SearchRouter', function () {
211

212 213 214 215
            beforeEach(function () {
                this.router = new SearchRouter();
                this.onSearch = jasmine.createSpy('onSearch');
                this.router.on('search', this.onSearch);
216 217
            });

218 219
            it ('has a search route', function () {
                expect(this.router.routes['search/:query']).toEqual('search');
220 221
            });

222 223 224 225
            it ('triggers a search event', function () {
                var query = 'mercury';
                this.router.search(query);
                expect(this.onSearch).toHaveBeenCalledWith(query);
226
            });
227 228 229

        });

230

231
        describe('SearchItemView', function () {
232

233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
            function beforeEachHelper(SearchItemView) {
                TemplateHelpers.installTemplates([
                    'templates/search/course_search_item',
                    'templates/search/dashboard_search_item'
                ]);

                this.model = new SearchResult({
                    location: ['section', 'subsection', 'unit'],
                    content_type: 'Video',
                    course_name: 'Course Name',
                    excerpt: 'A short excerpt.',
                    url: 'path/to/content'
                });

                this.seqModel = new SearchResult({
                    location: ['section', 'subsection'],
                    content_type: 'Sequence',
                    course_name: 'Course Name',
                    excerpt: 'A short excerpt.',
                    url: 'path/to/content'
                });

                this.item = new SearchItemView({ model: this.model });
                this.item.render();
                this.seqItem = new SearchItemView({ model: this.seqModel });
                this.seqItem.render();
            }

            function rendersItem() {
                expect(this.item.$el).toHaveAttr('role', 'region');
                expect(this.item.$el).toHaveAttr('aria-label', 'search result');
264
                expect(this.item.$el).toContainElement('a[href="' + this.model.get('url') + '"]');
265 266 267 268 269 270 271 272
                expect(this.item.$el.find('.result-type')).toContainHtml(this.model.get('content_type'));
                expect(this.item.$el.find('.result-excerpt')).toContainHtml(this.model.get('excerpt'));
                expect(this.item.$el.find('.result-location')).toContainHtml('section ▸ subsection ▸ unit');
            }

            function rendersSequentialItem() {
                expect(this.seqItem.$el).toHaveAttr('role', 'region');
                expect(this.seqItem.$el).toHaveAttr('aria-label', 'search result');
273
                expect(this.seqItem.$el).toContainElement('a[href="' + this.seqModel.get('url') + '"]');
274 275 276 277 278 279 280 281 282
                expect(this.seqItem.$el.find('.result-type')).toBeEmpty();
                expect(this.seqItem.$el.find('.result-excerpt')).toBeEmpty();
                expect(this.seqItem.$el.find('.result-location')).toContainHtml('section ▸ subsection');
            }

            function logsSearchItemViewEvent() {
                this.model.collection = new SearchCollection([this.model], { course_id: 'edx101' });
                this.item.render();
                // Mock the redirect call
283 284
                spyOn(this.item, 'redirect').and.callFake( function() {} );
                spyOn(Logger, 'log').and.returnValue($.Deferred().resolve());
285 286 287 288 289 290 291 292 293 294 295 296 297
                this.item.$el.find('a').trigger('click');
                expect(this.item.redirect).toHaveBeenCalled();
                this.item.$el.trigger('click');
                expect(this.item.redirect).toHaveBeenCalled();
            }

            describe('CourseSearchItemView', function () {
                beforeEach(function () {
                    beforeEachHelper.call(this, CourseSearchItemView);
                });
                it('renders items correctly', rendersItem);
                it('renders Sequence items correctly', rendersSequentialItem);
                it('logs view event', logsSearchItemViewEvent);
298
            });
299

300 301 302 303 304 305 306 307 308 309
            describe('DashSearchItemView', function () {
                beforeEach(function () {
                    beforeEachHelper.call(this, DashSearchItemView);
                });
                it('renders items correctly', rendersItem);
                it('renders Sequence items correctly', rendersSequentialItem);
                it('displays course name in breadcrumbs', function () {
                    expect(this.seqItem.$el.find('.result-course-name')).toContainHtml(this.model.get('course_name'));
                });
                it('logs view event', logsSearchItemViewEvent);
310
            });
311

312
        });
313 314


315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
        describe('SearchForm', function () {

            function trimsInputString() {
                var term = '    search string  ';
                $('.search-field').val(term);
                $('form').trigger('submit');
                expect(this.onSearch).toHaveBeenCalledWith($.trim(term));
            }

            function doesSearch() {
                var term = '  search string  ';
                $('.search-field').val(term);
                this.form.doSearch(term);
                expect(this.onSearch).toHaveBeenCalledWith($.trim(term));
                expect($('.search-field').val()).toEqual(term);
                expect($('.search-field')).toHaveClass('is-active');
                expect($('.search-button')).toBeHidden();
                expect($('.cancel-button')).toBeVisible();
            }

            function triggersSearchEvent() {
                var term = 'search string';
                $('.search-field').val(term);
                $('form').trigger('submit');
                expect(this.onSearch).toHaveBeenCalledWith(term);
                expect($('.search-field')).toHaveClass('is-active');
                expect($('.search-button')).toBeHidden();
                expect($('.cancel-button')).toBeVisible();
            }

            function clearsSearchOnCancel() {
                $('.search-field').val('search string');
                $('.search-button').trigger('click');
                $('.cancel-button').trigger('click');
                expect($('.search-field')).not.toHaveClass('is-active');
                expect($('.search-button')).toBeVisible();
                expect($('.cancel-button')).toBeHidden();
                expect($('.search-field')).toHaveValue('');
            }

            function clearsSearchOnEmpty() {
                $('.search-field').val('');
                $('form').trigger('submit');
                expect(this.onClear).toHaveBeenCalled();
                expect($('.search-field')).not.toHaveClass('is-active');
                expect($('.cancel-button')).toBeHidden();
                expect($('.search-button')).toBeVisible();
            }

364 365 366 367 368 369 370 371 372 373 374 375 376 377
            describe('CourseSearchForm', function () {
                beforeEach(function () {
                    loadFixtures('js/fixtures/search/course_search_form.html');
                    this.form = new CourseSearchForm();
                    this.onClear = jasmine.createSpy('onClear');
                    this.onSearch = jasmine.createSpy('onSearch');
                    this.form.on('clear', this.onClear);
                    this.form.on('search', this.onSearch);
                });
                it('trims input string', trimsInputString);
                it('handles calls to doSearch', doesSearch);
                it('triggers a search event and changes to active state', triggersSearchEvent);
                it('clears search when clicking on cancel button', clearsSearchOnCancel);
                it('clears search when search box is empty', clearsSearchOnEmpty);
378
            });
379

380 381 382 383 384 385 386 387 388 389 390 391 392 393
            describe('DashSearchForm', function () {
                beforeEach(function () {
                    loadFixtures('js/fixtures/search/dashboard_search_form.html');
                    this.form = new DashSearchForm();
                    this.onClear = jasmine.createSpy('onClear');
                    this.onSearch = jasmine.createSpy('onSearch');
                    this.form.on('clear', this.onClear);
                    this.form.on('search', this.onSearch);
                });
                it('trims input string', trimsInputString);
                it('handles calls to doSearch', doesSearch);
                it('triggers a search event and changes to active state', triggersSearchEvent);
                it('clears search when clicking on cancel button', clearsSearchOnCancel);
                it('clears search when search box is empty', clearsSearchOnEmpty);
394
            });
395

396 397
        });

398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416

        describe('SearchResultsView', function () {

            function showsLoadingMessage () {
                this.resultsView.showLoadingMessage();
                expect(this.resultsView.$contentElement).toBeHidden();
                expect(this.resultsView.$el).toBeVisible();
                expect(this.resultsView.$el).not.toBeEmpty();
            }

            function showsErrorMessage () {
                this.resultsView.showErrorMessage();
                expect(this.resultsView.$contentElement).toBeHidden();
                expect(this.resultsView.$el).toBeVisible();
                expect(this.resultsView.$el).not.toBeEmpty();
            }

            function returnsToContent () {
                this.resultsView.clear();
417
                expect(this.resultsView.$contentElement).toHaveCss({'display': this.contentElementDisplayValue});
418
                expect(this.resultsView.$el).toBeHidden();
419 420
                expect(this.resultsView.$el).toBeEmpty();
            }
421

422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
            function showsNoResultsMessage() {
                this.collection.reset();
                this.resultsView.render();
                expect(this.resultsView.$el).toContainHtml('no results');
                expect(this.resultsView.$el.find('ol')).not.toExist();
            }

            function rendersSearchResults () {
                var searchResults = [{
                    location: ['section', 'subsection', 'unit'],
                    url: '/some/url/to/content',
                    content_type: 'text',
                    course_name: '',
                    excerpt: 'this is a short excerpt'
                }];
                this.collection.set(searchResults);
                this.collection.latestModelsCount = 1;
                this.collection.totalCount = 1;
440

441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
                this.resultsView.render();
                expect(this.resultsView.$el.find('ol')[0]).toExist();
                expect(this.resultsView.$el.find('li').length).toEqual(1);
                expect(this.resultsView.$el).toContainHtml('Search Results');
                expect(this.resultsView.$el).toContainHtml('this is a short excerpt');

                this.collection.set(searchResults);
                this.collection.totalCount = 2;
                this.resultsView.renderNext();
                expect(this.resultsView.$el.find('.search-count')).toContainHtml('2');
                expect(this.resultsView.$el.find('li').length).toEqual(2);
            }

            function showsMoreResultsLink () {
                this.collection.totalCount = 123;
                this.collection.hasNextPage = function () { return true; };
                this.resultsView.render();
                expect(this.resultsView.$el.find('a.search-load-next')[0]).toExist();
459

460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
                this.collection.totalCount = 123;
                this.collection.hasNextPage = function () { return false; };
                this.resultsView.render();
                expect(this.resultsView.$el.find('a.search-load-next')[0]).not.toExist();
            }

            function triggersNextPageEvent () {
                var onNext = jasmine.createSpy('onNext');
                this.resultsView.on('next', onNext);
                this.collection.totalCount = 123;
                this.collection.hasNextPage = function () { return true; };
                this.resultsView.render();
                this.resultsView.$el.find('a.search-load-next').click();
                expect(onNext).toHaveBeenCalled();
            }
475

476 477 478 479 480 481 482 483 484 485 486 487 488
            function showsLoadMoreSpinner () {
                this.collection.totalCount = 123;
                this.collection.hasNextPage = function () { return true; };
                this.resultsView.render();
                expect(this.resultsView.$el.find('a.search-load-next .icon')).toBeHidden();
                this.resultsView.loadNext();
                // toBeVisible does not work with inline
                expect(this.resultsView.$el.find('a.search-load-next .icon')).toHaveCss({ 'display': 'inline' });
                this.resultsView.renderNext();
                expect(this.resultsView.$el.find('a.search-load-next .icon')).toBeHidden();
            }

            function beforeEachHelper(SearchResultsView) {
489
                appendSetFixtures(
490
                    '<div class="courseware-results"></div>' +
491 492
                    '<section id="course-content"></section>' +
                    '<section id="dashboard-search-results"></section>' +
493
                    '<section id="my-courses" tabindex="-1"></section>'
494
                );
495

496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
                TemplateHelpers.installTemplates([
                    'templates/search/course_search_item',
                    'templates/search/dashboard_search_item',
                    'templates/search/course_search_results',
                    'templates/search/dashboard_search_results',
                    'templates/search/search_loading',
                    'templates/search/search_error'
                ]);

                var MockCollection = Backbone.Collection.extend({
                    hasNextPage: function () {},
                    latestModelsCount: 0,
                    pageSize: 20,
                    latestModels: function () {
                        return SearchCollection.prototype.latestModels.apply(this, arguments);
                    }
                });
                this.collection = new MockCollection();
                this.resultsView = new SearchResultsView({ collection: this.collection });
            }

            describe('CourseSearchResultsView', function () {
                beforeEach(function() {
                    beforeEachHelper.call(this, CourseSearchResultsView);
520
                    this.contentElementDisplayValue = 'table-cell';
521 522 523 524 525 526 527 528 529
                });
                it('shows loading message', showsLoadingMessage);
                it('shows error message', showsErrorMessage);
                it('returns to content', returnsToContent);
                it('shows a message when there are no results', showsNoResultsMessage);
                it('renders search results', rendersSearchResults);
                it('shows a link to load more results', showsMoreResultsLink);
                it('triggers an event for next page', triggersNextPageEvent);
                it('shows a spinner when loading more results', showsLoadMoreSpinner);
530 531
            });

532 533 534
            describe('DashSearchResultsView', function () {
                beforeEach(function() {
                    beforeEachHelper.call(this, DashSearchResultsView);
535
                    this.contentElementDisplayValue = 'block';
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
                });
                it('shows loading message', showsLoadingMessage);
                it('shows error message', showsErrorMessage);
                it('returns to content', returnsToContent);
                it('shows a message when there are no results', showsNoResultsMessage);
                it('renders search results', rendersSearchResults);
                it('shows a link to load more results', showsMoreResultsLink);
                it('triggers an event for next page', triggersNextPageEvent);
                it('shows a spinner when loading more results', showsLoadMoreSpinner);
                it('returns back to courses', function () {
                    var onReset = jasmine.createSpy('onReset');
                    this.resultsView.on('reset', onReset);
                    this.resultsView.render();
                    expect(this.resultsView.$el.find('a.search-back-to-courses')).toExist();
                    this.resultsView.$el.find('.search-back-to-courses').click();
                    expect(onReset).toHaveBeenCalled();
                    expect(this.resultsView.$contentElement).toBeVisible();
                    expect(this.resultsView.$el).toBeHidden();
                });
            });
556 557 558 559

        });


560
        describe('SearchApp', function () {
561

562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
            function showsLoadingMessage () {
                $('.search-field').val('search string');
                $('.search-button').trigger('click');
                expect(this.$contentElement).toBeHidden();
                expect(this.$searchResults).toBeVisible();
                expect(this.$searchResults).not.toBeEmpty();
            }

            function performsSearch () {
                var requests = AjaxHelpers.requests(this);
                $('.search-field').val('search string');
                $('.search-button').trigger('click');
                AjaxHelpers.respondWithJson(requests, {
                    total: 1337,
                    access_denied_count: 12,
                    results: [{
                        data: {
                            location: ['section', 'subsection', 'unit'],
                            url: '/some/url/to/content',
                            content_type: 'text',
                            excerpt: 'this is a short excerpt',
                            course_name: ''
                        }
                    }]
                });
                expect($('.search-info')).toExist();
                expect($('.search-result-list')).toBeVisible();
                expect(this.$searchResults.find('li').length).toEqual(1);
            }
591

592
            function showsErrorMessage () {
593
                var requests = AjaxHelpers.requests(this);
594 595
                $('.search-field').val('search string');
                $('.search-button').trigger('click');
596 597 598 599 600 601 602
                AjaxHelpers.respondWithError(requests, 500, {});
                expect(this.$searchResults).toContainHtml('There was an error');
            }

            function updatesNavigationHistory () {
                $('.search-field').val('edx');
                $('.search-button').trigger('click');
603
                expect(Backbone.history.navigate.calls.mostRecent().args[0]).toContain('search/edx');
604
                $('.cancel-button').trigger('click');
605
                expect(Backbone.history.navigate.calls.argsFor(1)[0]).toBe('');
606 607 608 609 610 611 612
            }

            function cancelsSearchRequest () {
                var requests = AjaxHelpers.requests(this);
                // send search request to server
                $('.search-field').val('search string');
                $('.search-button').trigger('click');
613
                // cancel the search and then skip the request that was marked as reset
614
                $('.cancel-button').trigger('click');
615
                AjaxHelpers.skipResetRequest(requests);
616
                // there should be no results
617
                expect(this.$contentElement).toHaveCss({'display': this.contentElementDisplayValue});
618
                expect(this.$searchResults).toBeHidden();
619 620 621 622
            }

            function clearsResults () {
                $('.cancel-button').trigger('click');
623
                expect(this.$contentElement).toHaveCss({'display': this.contentElementDisplayValue});
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
                expect(this.$searchResults).toBeHidden();
            }

            function loadsNextPage () {
                var requests = AjaxHelpers.requests(this);
                var response = {
                    total: 1337,
                    access_denied_count: 12,
                    results: [{
                        data: {
                            location: ['section', 'subsection', 'unit'],
                            url: '/some/url/to/content',
                            content_type: 'text',
                            excerpt: 'this is a short excerpt',
                            course_name: ''
                        }
                    }]
                };
                $('.search-field').val('query');
                $('.search-button').trigger('click');
                AjaxHelpers.respondWithJson(requests, response);
                expect(this.$searchResults.find('li').length).toEqual(1);
                expect($('.search-load-next')).toBeVisible();
                $('.search-load-next').trigger('click');
                var body = requests[1].requestBody;
                expect(body).toContain('search_string=query');
                expect(body).toContain('page_index=1');
                AjaxHelpers.respondWithJson(requests, response);
                expect(this.$searchResults.find('li').length).toEqual(2);
            }

            function navigatesToSearch () {
                var requests = AjaxHelpers.requests(this);
657
                Backbone.history.start();
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
                Backbone.history.loadUrl('search/query');
                expect(requests[0].requestBody).toContain('search_string=query');
            }

            function loadTemplates () {
                TemplateHelpers.installTemplates([
                    'templates/search/course_search_item',
                    'templates/search/dashboard_search_item',
                    'templates/search/search_loading',
                    'templates/search/search_error',
                    'templates/search/course_search_results',
                    'templates/search/dashboard_search_results'
                ]);
            }

            describe('CourseSearchApp', function () {

                beforeEach(function () {
                    loadFixtures('js/fixtures/search/course_search_form.html');
                    appendSetFixtures(
678
                        '<div class="courseware-results"></div>' +
679 680 681 682 683 684 685 686
                        '<section id="course-content"></section>'
                    );
                    loadTemplates.call(this);

                    var courseId = 'a/b/c';
                    CourseSearchFactory(courseId);
                    spyOn(Backbone.history, 'navigate');
                    this.$contentElement = $('#course-content');
687
                    this.contentElementDisplayValue = 'table-cell';
688
                    this.$searchResults = $('.courseware-results');
689 690
                });

691 692 693 694
                afterEach(function (){
                    Backbone.history.stop();
                });

695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
                it('shows loading message on search', showsLoadingMessage);
                it('performs search', performsSearch);
                it('shows an error message', showsErrorMessage);
                it('updates navigation history', updatesNavigationHistory);
                it('cancels search request', cancelsSearchRequest);
                it('clears results', clearsResults);
                it('loads next page', loadsNextPage);
                it('navigates to search', navigatesToSearch);

            });

            describe('DashSearchApp', function () {

                beforeEach(function () {
                    loadFixtures('js/fixtures/search/dashboard_search_form.html');
                    appendSetFixtures(
                        '<section id="dashboard-search-results"></section>' +
712
                        '<section id="my-courses" tabindex="-1"></section>'
713 714 715 716 717 718
                    );
                    loadTemplates.call(this);
                    DashboardSearchFactory();

                    spyOn(Backbone.history, 'navigate');
                    this.$contentElement = $('#my-courses');
719
                    this.contentElementDisplayValue = 'block';
720 721 722
                    this.$searchResults = $('#dashboard-search-results');
                });

723 724 725 726
                afterEach(function (){
                    Backbone.history.stop();
                });

727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
                it('shows loading message on search', showsLoadingMessage);
                it('performs search', performsSearch);
                it('shows an error message', showsErrorMessage);
                it('updates navigation history', updatesNavigationHistory);
                it('cancels search request', cancelsSearchRequest);
                it('clears results', clearsResults);
                it('loads next page', loadsNextPage);
                it('navigates to search', navigatesToSearch);
                it('returns to course list', function () {
                    var requests = AjaxHelpers.requests(this);
                    $('.search-field').val('search string');
                    $('.search-button').trigger('click');
                    AjaxHelpers.respondWithJson(requests, {
                        total: 1337,
                        access_denied_count: 12,
                        results: [{
                            data: {
                                location: ['section', 'subsection', 'unit'],
                                url: '/some/url/to/content',
                                content_type: 'text',
                                excerpt: 'this is a short excerpt',
                                course_name: ''
                            }
                        }]
                    });
                    expect($('.search-back-to-courses')).toExist();
                    $('.search-back-to-courses').trigger('click');
                    expect(this.$contentElement).toBeVisible();
                    expect(this.$searchResults).toBeHidden();
                    expect(this.$searchResults).toBeEmpty();
                });

759 760
            });

761 762 763
        });

    });
764
});