Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Make search and filter stores namespaced (#316)
Olga Bulat0e12e3a79c7d
diff --git a/src/components/AudioDetails/Table.vue b/src/components/AudioDetails/Table.vueindex 15521ea1a..2c795ef66 100644--- a/src/components/AudioDetails/Table.vue+++ b/src/components/AudioDetails/Table.vue@@ -72,22 +72,19 @@<script>import getProviderName from '~/utils/get-provider-name'+import { PROVIDER } from '~/constants/store-modules'+import { mapState } from 'vuex'export default {name: 'AudioDetailsTable',props: ['audio'],computed: {+ ...mapState(PROVIDER, ['audioProviders']),providerName() {- return getProviderName(- this.$store.state.audioProviders,- this.$props.audio.provider- )+ return getProviderName(this.audioProviders, this.$props.audio.provider)},sourceName() {- return getProviderName(- this.$store.state.audioProviders,- this.$props.audio.source- )+ return getProviderName(this.audioProviders, this.$props.audio.source)},},}diff --git a/src/components/AudioDetails/Tags.vue b/src/components/AudioDetails/Tags.vueindex 3e0e844b8..4379d669b 100644--- a/src/components/AudioDetails/Tags.vue+++ b/src/components/AudioDetails/Tags.vue@@ -17,7 +17,9 @@</template><script>-import { SET_QUERY } from '~/constants/mutation-types'+import { SET_Q } from '~/constants/mutation-types'+import { SEARCH } from '~/constants/store-modules'+import { mapMutations } from 'vuex'export default {name: 'AudioTags',@@ -28,11 +30,12 @@ export default {},},methods: {+ ...mapMutations(SEARCH, { setSearchTerm: SET_Q }),isClarifaiTag(provider) {return provider === 'clarifai'},searchByTagName(query) {- this.$store.commit(SET_QUERY, { query: { q: query } })+ this.setSearchTerm({ q: query })},getValidTags() {return this.$props.tags.filter((tag) => !!tag.name)diff --git a/src/components/AudioResultsList.vue b/src/components/AudioResultsList.vueindex 49b6e455c..c92a7d905 100644--- a/src/components/AudioResultsList.vue+++ b/src/components/AudioResultsList.vue@@ -1,8 +1,8 @@<template><section>- <div v-show="!isFetchingAudios && includeAnalytics" class="results-meta">+ <div v-show="!isFetching" class="results-meta"><span class="caption font-semibold">- {{ audiosCount }}+ {{ _audiosCount }}</span></div><div class="px-6 pt-6">@@ -14,9 +14,9 @@layout="row"/></div>- <div v-if="!isFetchingAudiosError" class="load-more">+ <div v-if="!isFetchingError" class="load-more"><button- v-show="!isFetchingAudios && includeAnalytics"+ v-show="!isFetching"class="button":disabled="isFinished"@click="onLoadMoreAudios"@@ -29,9 +29,9 @@}}</span><span v-else>{{ $t('browse-page.load') }}</span></button>- <LoadingIcon v-show="isFetchingAudios" />+ <LoadingIcon v-show="isFetching" /></div>- <div v-if="isFetchingAudiosError" class="m-auto w-1/2 text-center pt-6">+ <div v-if="isFetchingError" class="m-auto w-1/2 text-center pt-6"><h5>{{$t('browse-page.fetching-error', {@@ -45,17 +45,13 @@</template><script>+import { mapActions, mapGetters, mapState } from 'vuex'import { FETCH_MEDIA } from '~/constants/action-types'import { AUDIO } from '~/constants/media'-import { mapActions, mapState } from 'vuex'+import { FILTER, SEARCH } from '~/constants/store-modules'export default {name: 'AudioResultsList',- props: {- includeAnalytics: {- default: true,- },- },async fetch() {if (!this.audios.length) {await this.fetchMedia({@@ -65,16 +61,18 @@ export default {}},computed: {- ...mapState(['audios', 'errorMessage', 'isFilterVisible', 'query']),- ...mapState({- isFetchingAudios: 'isFetching.audios',- isFetchingAudiosError: 'isFetchingError.audios',- resultsCount: 'audiosCount',- currentPage: 'audioPage',- audioPageCount: 'pageCount.audios',- }),- audiosCount() {- const count = this.resultsCount+ ...mapState(SEARCH, [+ 'audios',+ 'errorMessage',+ 'audiosCount',+ 'audioPage',+ 'pageCount',+ 'query',+ ]),+ ...mapGetters(SEARCH, ['isFetching', 'isFetchingError']),+ ...mapState(FILTER, ['isFilterVisible']),+ _audiosCount() {+ const count = this.audiosCountif (count === 0) {return this.$t('browse-page.audio-no-results')}@@ -87,19 +85,17 @@ export default {})},isFinished() {- return this.currentPage >= this.audioPageCount+ return this.audioPage >= this.pageCount.audio},audioTrackSize() {return this.isFilterVisible ? 'm' : 's'},},methods: {- ...mapActions({- fetchMedia: FETCH_MEDIA,- }),+ ...mapActions(SEARCH, { fetchMedia: FETCH_MEDIA }),onLoadMoreAudios() {const searchParams = {- page: this.currentPage + 1,+ page: this.audioPage + 1,shouldPersistMedia: true,...this.query,}diff --git a/src/components/ContentReport/ContentReportForm.vue b/src/components/ContentReport/ContentReportForm.vueindex fd0a6721f..9831dfc0a 100644--- a/src/components/ContentReport/ContentReportForm.vue+++ b/src/components/ContentReport/ContentReportForm.vue@@ -102,6 +102,7 @@ import ReportError from './ReportError'import { SEND_CONTENT_REPORT } from '~/constants/action-types'import { REPORT_FORM_CLOSED } from '~/constants/mutation-types'import { PROVIDER, REPORT_CONTENT } from '~/constants/store-modules'+import { mapActions, mapMutations, mapState } from 'vuex'const dmcaFormUrl ='https://docs.google.com/forms/d/e/1FAIpQLSd0I8GsEbGQLdaX4K_F6V2NbHZqN137WMZgnptUpzwd-kbDKA/viewform'@@ -124,20 +125,15 @@ export default {}},computed: {- isReportSent() {- return this.$store.state[REPORT_CONTENT].isReportSent- },- reportFailed() {- return this.$store.state[REPORT_CONTENT].reportFailed- },+ ...mapState(REPORT_CONTENT, ['isReportSent', 'reportFailed']),+ ...mapState(PROVIDER, ['imageProviders']),providerName() {- return getProviderName(- this.$store.state[PROVIDER].imageProviders,- this.image.provider- )+ return getProviderName(this.imageProviders, this.image.provider)},},methods: {+ ...mapActions(REPORT_CONTENT, { sendReport: SEND_CONTENT_REPORT }),+ ...mapMutations(REPORT_CONTENT, { closeReportForm: REPORT_FORM_CLOSED }),onIssueSelected() {if (this.selectedReason === 'other') {this.selectedOther = true@@ -152,14 +148,14 @@ export default {this.selectedCopyright = false},sendContentReport(description = '') {- this.$store.dispatch(`${REPORT_CONTENT}/${SEND_CONTENT_REPORT}`, {+ this.sendReport({identifier: this.$props.image.id,reason: this.selectedReason,description,})},closeForm() {- this.$store.commit(`${REPORT_CONTENT}/${REPORT_FORM_CLOSED}`)+ this.closeReportForm},},}diff --git a/src/components/ContentReport/ReportError.vue b/src/components/ContentReport/ReportError.vueindex 9fa8fea25..19942ce25 100644--- a/src/components/ContentReport/ReportError.vue+++ b/src/components/ContentReport/ReportError.vue@@ -18,12 +18,13 @@<script>import { BACK_TO_REPORT_START } from '~/constants/mutation-types'+import { REPORT_CONTENT } from '~/constants/store-modules'export default {name: 'ReportError',methods: {onBackClick() {- this.$store.commit(BACK_TO_REPORT_START)+ this.$store.commit(`${REPORT_CONTENT}/${BACK_TO_REPORT_START}`)},},}diff --git a/src/components/EmbeddedNavSection.vue b/src/components/EmbeddedNavSection.vueindex e6a97dd5f..529582e73 100644--- a/src/components/EmbeddedNavSection.vue+++ b/src/components/EmbeddedNavSection.vue@@ -124,8 +124,10 @@</template><script>-import { SET_QUERY } from '~/constants/mutation-types'+import { SET_Q } from '~/constants/mutation-types'import Dropdown from '~/components/Dropdown'+import { SEARCH } from '~/constants/store-modules'+import { mapMutations } from 'vuex'export default {name: 'EmbeddedNavSection',@@ -142,11 +144,13 @@ export default {},},methods: {+ ...mapMutations(SEARCH, { setSearchTerm: SET_Q }),onSubmit() {- this.$store.commit(SET_QUERY, { query: { q: this.form.searchTerm } })+ const q = this.form.searchTerm+ this.setSearchTerm({ q })const newPath = this.localePath({path: '/search',- query: { q: this.form.searchTerm },+ query: { q },})this.$router.push(newPath)},diff --git a/src/components/Filters/FilterChecklist.vue b/src/components/Filters/FilterChecklist.vueindex 25100c03c..6f1741c0b 100644--- a/src/components/Filters/FilterChecklist.vue+++ b/src/components/Filters/FilterChecklist.vue@@ -150,7 +150,7 @@ export default {this.licenseExplanationVisible = false},getFilterTypeValue(filterKey, val) {- return this.$store.state.filters[filterKey].filter((item) =>+ return this.$store.state.filter.filters[filterKey].filter((item) =>item.code.includes(val))},diff --git a/src/components/Filters/FilterDisplay.vue b/src/components/Filters/FilterDisplay.vueindex dd866e523..6de51efbd 100644--- a/src/components/Filters/FilterDisplay.vue+++ b/src/components/Filters/FilterDisplay.vue@@ -19,16 +19,17 @@import { TOGGLE_FILTER } from '~/constants/action-types'import FilterTag from '~/components/Filters/FilterTag'import { mapGetters } from 'vuex'+import { FILTER } from '~/constants/store-modules'export default {name: 'FilterDisplay',components: { FilterTag },computed: {- ...mapGetters(['appliedFilterTags', 'isAnyFilterApplied']),+ ...mapGetters(FILTER, ['appliedFilterTags', 'isAnyFilterApplied']),},methods: {onUpdateFilter({ code, filterType }) {- this.$store.dispatch(TOGGLE_FILTER, { code, filterType })+ this.$store.dispatch(`${FILTER}/${TOGGLE_FILTER}`, { code, filterType })},},}diff --git a/src/components/Filters/FiltersList.vue b/src/components/Filters/FiltersList.vueindex 0b0fd1371..339bf6942 100644--- a/src/components/Filters/FiltersList.vue+++ b/src/components/Filters/FiltersList.vue@@ -49,10 +49,11 @@</template><script>-import { mapGetters } from 'vuex'+import { mapGetters, mapState } from 'vuex'import { kebabize } from '~/utils/format-strings'import { AUDIO, IMAGE, VIDEO } from '~/constants/media'import FilterChecklist from './FilterChecklist'+import { FILTER, SEARCH } from '~/constants/store-modules'export default {name: 'FiltersList',@@ -60,7 +61,8 @@ export default {FilterChecklist,},computed: {- ...mapGetters([+ ...mapState(SEARCH, ['searchType']),+ ...mapGetters(FILTER, ['audioFiltersForDisplay','imageFiltersForDisplay','videoFiltersForDisplay',@@ -68,7 +70,7 @@ export default {'isAnyFilterApplied',]),filters() {- switch (this.$store.state.searchType) {+ switch (this.searchType) {case AUDIO:return this.audioFiltersForDisplaycase IMAGE:diff --git a/src/components/Filters/SearchGridFilter.vue b/src/components/Filters/SearchGridFilter.vueindex 6bf026d93..25033bb69 100644--- a/src/components/Filters/SearchGridFilter.vue+++ b/src/components/Filters/SearchGridFilter.vue@@ -4,6 +4,7 @@'search-filters': true,'search-filters__visible': isFilterVisible,}"+ data-testid="filters-list"@onUpdateFilter="onUpdateFilter"@onToggleSearchGridFilter="onToggleSearchGridFilter"@onClearFilters="onClearFilters"@@ -17,27 +18,22 @@ import {CLEAR_FILTERS,} from '~/constants/mutation-types'import { TOGGLE_FILTER } from '~/constants/action-types'+import { FILTER } from '~/constants/store-modules'+import FiltersList from '~/components/Filters/FiltersList'export default {name: 'SearchGridFilter',+ components: { FiltersList },computed: {- ...mapState(['filters', 'isFilterVisible']),- /**- * Show filters expanded by default- * @todo: The A/B test is over and we're going with the expanded view. Can remove a lot of this old test logic- */-- filtersExpandedByDefault() {- return true- },+ ...mapState(FILTER, ['filters', 'isFilterVisible']),},methods: {- ...mapActions({+ ...mapActions(FILTER, {toggleFilter: TOGGLE_FILTER,+ clearFilters: CLEAR_FILTERS,}),- ...mapMutations({+ ...mapMutations(FILTER, {setFilterVisible: SET_FILTER_IS_VISIBLE,- clearFilters: CLEAR_FILTERS,}),onUpdateFilter({ code, filterType }) {this.toggleFilter({ code, filterType })diff --git a/src/components/HeroSection.vue b/src/components/HeroSection.vueindex 842ed5bf8..3e9af5205 100644--- a/src/components/HeroSection.vue+++ b/src/components/HeroSection.vue@@ -65,12 +65,17 @@</template><script>-import { SET_QUERY, SET_SEARCH_TYPE } from '~/constants/mutation-types'+import { SET_Q, SET_SEARCH_TYPE } from '~/constants/mutation-types'import { filtersToQueryData } from '~/utils/search-query-transform'import { ALL_MEDIA } from '~/constants/media'+import { SEARCH } from '~/constants/store-modules'+import { mapMutations } from 'vuex'+import HomeLicenseFilter from '~/components/HomeLicenseFilter'+import SearchTypeToggle from '~/components/SearchTypeToggle'export default {name: 'HeroSection',+ components: { HomeLicenseFilter, SearchTypeToggle },/*** @return {{ form: { searchTerm: string, searchType: 'image' | 'audio' }, showSearchType: boolean }}*/@@ -84,6 +89,10 @@ export default {}},methods: {+ ...mapMutations(SEARCH, {+ setSearchTerm: SET_Q,+ setSearchType: SET_SEARCH_TYPE,+ }),getPath() {if (!process.env.enableAudio) return '/search'@@ -95,19 +104,20 @@ export default {return this.form.searchType},onSubmit() {- this.$store.commit(SET_QUERY, { query: { q: this.form.searchTerm } })+ this.setSearchTerm({ q: this.form.searchTerm })if (process.env.enableAudio) {- this.$store.commit(SET_SEARCH_TYPE, {- searchType: this.form.searchType,- })+ this.setSearchType({ searchType: this.form.searchType })}const newPath = this.localePath({path: this.getPath(),query: {q: this.form.searchTerm,- ...filtersToQueryData(this.$store.state.filters, this.getMediaType()),+ ...filtersToQueryData(+ this.$store.state.filter.filters,+ this.getMediaType()+ ),},})this.$router.push(newPath)diff --git a/src/components/HomeLicenseFilter.vue b/src/components/HomeLicenseFilter.vueindex f77b2bd53..ba5e9bc4e 100644--- a/src/components/HomeLicenseFilter.vue+++ b/src/components/HomeLicenseFilter.vue@@ -20,19 +20,20 @@</template><script>-import { mapActions, mapState } from 'vuex'import { TOGGLE_FILTER } from '~/constants/action-types'+import { FILTER } from '~/constants/store-modules'+import { mapActions, mapState } from 'vuex'export default {name: 'LicenseFilter',computed: {- ...mapState(['filters']),+ ...mapState(FILTER, ['filters']),licenseTypes() {return this.filters.licenseTypes},},methods: {- ...mapActions({ toggleFilter: TOGGLE_FILTER }),+ ...mapActions(FILTER, { toggleFilter: TOGGLE_FILTER }),onFilterChanged(code) {this.toggleFilter({code,diff --git a/src/components/ImageDetails/ImageInfo.vue b/src/components/ImageDetails/ImageInfo.vueindex 1a7883677..7f47a6fa2 100644--- a/src/components/ImageDetails/ImageInfo.vue+++ b/src/components/ImageDetails/ImageInfo.vue@@ -54,7 +54,8 @@ import {import PhotoTags from '~/components/PhotoTags'import getProviderName from '~/utils/get-provider-name'import getProviderLogo from '~/utils/get-provider-logo'-import { USAGE_DATA } from '~/constants/store-modules'+import { PROVIDER, USAGE_DATA } from '~/constants/store-modules'+import { mapActions, mapState } from 'vuex'export default {name: 'ImageInfo',@@ -70,11 +71,9 @@ export default {'imageType',],computed: {+ ...mapState(PROVIDER, ['imageProviders']),providerName() {- return getProviderName(- this.$store.state.imageProviders,- this.$props.image.provider- )+ return getProviderName(this.imageProviders, this.$props.image.provider)},prettyImageType() {if (this.imageType && this.imageType.split('/').length > 1) {@@ -83,18 +82,16 @@ export default {return 'Unknown'},sourceName() {- return getProviderName(- this.$store.state.imageProviders,- this.$props.image.source- )+ return getProviderName(this.imageProviders, this.$props.image.source)},},methods: {+ ...mapActions(USAGE_DATA, { sendEvent: SEND_DETAIL_PAGE_EVENT }),getProviderLogo(providerName) {return getProviderLogo(providerName)},onPhotoSourceLinkClicked() {- this.$store.dispatch(`${USAGE_DATA}/${SEND_DETAIL_PAGE_EVENT}`, {+ this.sendEvent({eventType: DETAIL_PAGE_EVENTS.SOURCE_CLICKED,resultUuid: this.$props.image.id,})diff --git a/src/components/MetaSearch/MetaSearchForm.vue b/src/components/MetaSearch/MetaSearchForm.vueindex 9033febd0..fd2d42d6b 100644--- a/src/components/MetaSearch/MetaSearchForm.vue+++ b/src/components/MetaSearch/MetaSearchForm.vue@@ -48,6 +48,8 @@<script>import MetaSourceList from './MetaSourceList'import { AUDIO, IMAGE, VIDEO } from '~/constants/media'+import { mapState } from 'vuex'+import { SEARCH } from '~/constants/store-modules'export default {name: 'MetaSearch',@@ -60,9 +62,7 @@ export default {noresult: { type: Boolean, required: true },},computed: {- query() {- return this.$store.state.query- },+ ...mapState(SEARCH, ['query']),unsupportedByUsefilter() {if (this.type === AUDIO) {return 'CC Mixter, Jamendo, or Wikimedia Commons'diff --git a/src/components/NavSection.vue b/src/components/NavSection.vueindex 62507ea50..a02580a9f 100644--- a/src/components/NavSection.vue+++ b/src/components/NavSection.vue@@ -125,8 +125,10 @@</template><script>-import { SET_QUERY } from '~/constants/mutation-types'+import { SET_Q } from '~/constants/mutation-types'import Dropdown from '~/components/Dropdown'+import { SEARCH } from '~/constants/store-modules'+import { mapMutations } from 'vuex'export default {name: 'NavSection',@@ -143,11 +145,14 @@ export default {},},methods: {+ ...mapMutations(SEARCH, { setSearchTerm: SET_Q }),onSubmit() {- this.$store.commit(SET_QUERY, { query: { q: this.form.searchTerm } })+ const q = this.form.searchTerm+ const theArgs = { q }+ this.setSearchTerm(theArgs)const newPath = this.localePath({path: '/search',- query: { q: this.form.searchTerm },+ query: { q },})this.$router.push(newPath)},diff --git a/src/components/NotificationBanner.vue b/src/components/NotificationBanner.vueindex 6d0d9371d..10d2d10d7 100644--- a/src/components/NotificationBanner.vue+++ b/src/components/NotificationBanner.vue@@ -42,7 +42,7 @@ import { NOTIFICATION_ACTION } from '~/constants/action-types'export default {name: 'NotificationBanner',computed: {- ...mapState('notification', [+ ...mapState(NOTIFICATION, ['notificationText','notificationDismiss','notificationOkay',diff --git a/src/components/PhotoTags.vue b/src/components/PhotoTags.vueindex 9b6641b7c..ca9c2daea 100644--- a/src/components/PhotoTags.vue+++ b/src/components/PhotoTags.vue@@ -19,7 +19,9 @@</template><script>-import { SET_QUERY } from '~/constants/mutation-types'+import { SET_Q } from '~/constants/mutation-types'+import { SEARCH } from '~/constants/store-modules'+import { mapMutations } from 'vuex'export default {name: 'PhotoTags',@@ -30,11 +32,12 @@ export default {},},methods: {+ ...mapMutations(SEARCH, { setSearchTerm: SET_Q }),isClarifaiTag(provider) {return provider === 'clarifai'},searchByTagName(query) {- this.$store.commit(SET_QUERY, { query: { q: query } })+ this.setSearchTerm({ q: query })},getValidTags() {return this.$props.tags.filter((tag) => !!tag.name)diff --git a/src/components/SaferBrowsing.vue b/src/components/SaferBrowsing.vueindex a8ae36f28..4f42c9ec6 100644--- a/src/components/SaferBrowsing.vue+++ b/src/components/SaferBrowsing.vue@@ -43,6 +43,7 @@import { FocusTrap } from 'focus-trap-vue'import { TOGGLE_FILTER } from '~/constants/action-types'import { mapActions } from 'vuex'+import { FILTER } from '~/constants/store-modules'export default {name: 'SaferBrowsing',@@ -56,11 +57,11 @@ export default {},computed: {mature() {- return this.$store.state.filters.mature+ return this.$store.state.filter.filters.mature},},methods: {- ...mapActions({ toggleFilter: TOGGLE_FILTER }),+ ...mapActions(FILTER, { toggleFilter: TOGGLE_FILTER }),toggleShowForm() {this.showForm = !this.showForm},diff --git a/src/components/SearchGrid.vue b/src/components/SearchGrid.vueindex e1483030c..3cb5ac149 100644--- a/src/components/SearchGrid.vue+++ b/src/components/SearchGrid.vue@@ -8,13 +8,14 @@</template><script>+import { mapState } from 'vuex'+import { SEARCH } from '~/constants/store-modules'+export default {name: 'SearchGrid',props: ['searchTerm'],computed: {- query() {- return this.$store.state.query- },+ ...mapState(SEARCH, ['query']),},methods: {onLoadMoreImages(searchParams) {diff --git a/src/components/SearchGridForm.vue b/src/components/SearchGridForm.vueindex 443d6e9ab..e5a4ab9a8 100644--- a/src/components/SearchGridForm.vue+++ b/src/components/SearchGridForm.vue@@ -63,19 +63,20 @@import { SET_FILTER_IS_VISIBLE } from '~/constants/mutation-types'import { queryStringToSearchType } from '~/utils/search-query-transform'import { VIDEO } from '~/constants/media'+import { FILTER, SEARCH } from '~/constants/store-modules'+import { mapMutations, mapState } from 'vuex'export default {name: 'SearchGridForm',data: () => ({ searchTermsModel: null }),computed: {- activeTab() {- return queryStringToSearchType(this.$route.path)- },+ ...mapState(FILTER, ['isFilterVisible']),+ ...mapState(SEARCH, ['query']),searchTerms() {- return this.$store.state.query.q+ return this.query.q},- isFilterVisible() {- return this.$store.state.isFilterVisible+ activeTab() {+ return queryStringToSearchType(this.$route.path)},searchBoxPlaceholder() {return this.$t('browse-page.search-form.placeholder', {@@ -92,6 +93,7 @@ export default {this.setFormInput()},methods: {+ ...mapMutations(FILTER, { setFilterIsVisible: SET_FILTER_IS_VISIBLE }),onSubmit(e) {e.preventDefault()if (this.searchTermsModel) {@@ -110,7 +112,7 @@ export default {}},onToggleSearchGridFilter() {- this.$store.commit(SET_FILTER_IS_VISIBLE, {+ this.setFilterIsVisible({isFilterVisible: !this.isFilterVisible,})},diff --git a/src/components/SearchGridManualLoad.vue b/src/components/SearchGridManualLoad.vueindex d0c4834f4..8f4122cb6 100644--- a/src/components/SearchGridManualLoad.vue+++ b/src/components/SearchGridManualLoad.vue@@ -7,27 +7,24 @@}"><div ref="gridItems" class="search-grid_ctr">- <div v-show="!isFetchingImages && includeAnalytics" class="results-meta">+ <div v-show="!isFetching && includeAnalytics" class="results-meta"><span class="caption font-semibold">{{ _imagesCount }}</span>- <div class="hidden desk:block mr-auto pl-6">- <SearchRating v-if="_query.q" :search-term="_query.q" />- </div>- <div class="desk:hidden">- <SearchRating v-if="_query.q" :search-term="searchTerm" />+ <div class="hidden desk:block desk:mr-auto desk:pl-6">+ <SearchRating v-if="searchTerm" :search-term="searchTerm" /></div><SaferBrowsing /></div><div class="search-grid-cells"><SearchGridCell- v-for="(image, index) in _images"+ v-for="(image, index) in images":key="index":image="image"/></div><div- v-if="isFetchingImagesError"+ v-if="isFetchingError"class="search-grid_notification callout alert"><h5>@@ -36,24 +33,24 @@type: $t('browse-page.search-form.audio'),})}}- {{ _errorMessage }}+ {{ errorMessage }}</h5></div><div class="pb-6">- <div v-if="!isFetchingImagesError && !isFinished" class="load-more">+ <div v-if="!isFetchingError && !isFinished" class="load-more"><button- v-show="!isFetchingImages && includeAnalytics"+ v-show="!isFetching && includeAnalytics"class="button"@click="onLoadMoreImages"@keyup.enter="onLoadMoreImages"><span>{{ $t('browse-page.load') }}</span></button>- <LoadingIcon v-show="isFetchingImages" />+ <LoadingIcon v-show="isFetching" /></div><MetaSearchFormtype="image"- :noresult="storeImagesCount === 0"+ :noresult="imagesCount === 0":supported="true"/></div>@@ -65,18 +62,12 @@import { FETCH_MEDIA } from '~/constants/action-types'import { SET_MEDIA } from '~/constants/mutation-types'import { IMAGE } from '~/constants/media'-import { mapActions, mapMutations, mapState } from 'vuex'+import { mapActions, mapGetters, mapMutations, mapState } from 'vuex'+import { SEARCH } from '~/constants/store-modules'export default {name: 'SearchGridManualLoad',props: {- imagesCount: {- default: 0,- },- images: {- default: () => [],- },- query: {},useInfiniteScroll: {default: true,},@@ -96,29 +87,24 @@ export default {showMetaImageSearch: false,}),async fetch() {- if (!this.storeImages.length) {+ if (!this.images.length) {await this.fetchMedia({- ...this.$store.state.query,+ ...this.query,mediaType: IMAGE,})}},computed: {- ...mapState({- isFetchingImages: 'isFetching.images',- isFetchingImagesError: 'isFetchingError.images',- storeImages: 'images',- storeImagesCount: 'imagesCount',- currentPage: 'imagePage',- _errorMessage: 'errorMessage',- }),- _images() {- return this.useInfiniteScroll ? this.storeImages : this.images- },+ ...mapState(SEARCH, [+ 'imagesCount',+ 'imagePage',+ 'errorMessage',+ 'images',+ 'query',+ ]),+ ...mapGetters(SEARCH, ['isFetching', 'isFetchingError']),_imagesCount() {- const count = this.useInfiniteScroll- ? this.storeImagesCount- : this.imagesCount+ const count = this.imagesCountif (count === 0) {return this.$t('browse-page.image-no-results')}@@ -131,10 +117,10 @@ export default {})},_query() {- return this.$props.query+ return this.query},isFinished() {- return this.currentPage >= this.$store.state.pageCount.images+ return this.imagePage >= this.$store.state.search.pageCount.images},},watch: {@@ -146,18 +132,14 @@ export default {},},methods: {- ...mapMutations({- setMedia: SET_MEDIA,- }),- ...mapActions({- fetchMedia: FETCH_MEDIA,- }),+ ...mapMutations(SEARCH, { setMedia: SET_MEDIA }),+ ...mapActions(SEARCH, { fetchMedia: FETCH_MEDIA }),searchChanged() {this.setMedia({ media: [], page: 1 })},onLoadMoreImages() {const searchParams = {- page: this.currentPage + 1,+ page: this.imagePage + 1,shouldPersistMedia: true,...this._query,}diff --git a/src/constants/action-types.js b/src/constants/action-types.jsindex a52a36c95..185a03010 100644--- a/src/constants/action-types.js+++ b/src/constants/action-types.js@@ -1,14 +1,10 @@export const FETCH_MEDIA_TYPE_PROVIDERS = 'FETCH_MEDIA_TYPE_PROVIDERS'export const FETCH_MEDIA_PROVIDERS = 'FETCH_MEDIA_PROVIDERS'-export const ADD_FAVORITE = 'ADD_FAVORITE'export const FETCH_AUDIO = 'FETCH_AUDIO'export const FETCH_IMAGE = 'FETCH_IMAGE'export const FETCH_MEDIA = 'FETCH_MEDIA'-export const FETCH_RELATED_MEDIA = 'FETCH_RELATED_MEDIA'-export const RESET_RELATED_MEDIA = 'RESET_RELATED_MEDIA'export const COPY_ATTRIBUTION = 'COPY_ATTRIBUTION'export const REPORT_BUG = 'REPORT_BUG'-export const FETCH_COLLECTION_IMAGES = 'FETCH_COLLECTION_IMAGES'export const CONVERT_AB_TEST_EXPERIMENT = 'CONVERT_AB_TEST_EXPERIMENT'export const HANDLE_MEDIA_ERROR = 'HANDLE_MEDIA_ERROR'export const TOGGLE_FILTER = 'TOGGLE_FILTER'@@ -17,3 +13,5 @@ export const SET_SEARCH_TYPE_FROM_URL = 'SET_SEARCH_TYPE_FROM_URL'export const UPDATE_SEARCH_TYPE = 'UPDATE_SEARCH_TYPE'export const HANDLE_NO_MEDIA = 'HANDLE_NO_MEDIA'export const NOTIFICATION_ACTION = 'NOTIFICATION_ACTION'+export const UPDATE_QUERY = 'UPDATE_QUERY'+export const SET_FILTERS_FROM_URL = 'SET_FILTERS_FROM_URL'diff --git a/src/constants/mutation-types.js b/src/constants/mutation-types.jsindex fbf349e83..16fa56263 100644--- a/src/constants/mutation-types.js+++ b/src/constants/mutation-types.js@@ -6,19 +6,15 @@ export const FETCH_MEDIA_ERROR = 'FETCH_MEDIA_ERROR'export const MEDIA_NOT_FOUND = 'MEDIA_NOT_FOUND'export const FETCH_START_MEDIA = 'FETCH_START_MEDIA'export const SET_FILTER = 'SET_FILTER'-export const SET_FILTERS_FROM_URL = 'SET_FILTERS_FROM_URL'export const CLEAR_FILTERS = 'CLEAR_FILTERS'export const SET_FILTER_IS_VISIBLE = 'SET_FILTER_IS_VISIBLE'-export const SET_GRID_FILTER = 'SET_GRID_FILTER'export const SET_AUDIO = 'SET_AUDIO'export const SET_IMAGE = 'SET_IMAGE'export const SET_IMAGE_PAGE = 'SET_IMAGE_PAGE'export const SET_MEDIA_PROVIDERS = 'SET_MEDIA_PROVIDERS'export const SET_PROVIDERS_FILTERS = 'SET_PROVIDERS_FILTERS'export const SET_MEDIA = 'SET_MEDIA'-export const SET_IS_PAGE_CHANGE = 'SET_IS_PAGE_CHANGE'export const SET_QUERY = 'SET_QUERY'-export const SET_RELATED_MEDIA = 'SET_RELATED_MEDIA'export const REPORT_BUG_START = 'REPORT_BUG_START'export const REPORT_BUG_END = 'REPORT_BUG_END'export const REPORT_BUG_FAILED = 'REPORT_BUG_FAILED'@@ -28,7 +24,6 @@ export const REPORT_SENT = 'REPORT_SENT'export const REPORT_ERROR = 'REPORT_ERROR'export const BACK_TO_REPORT_START = 'BACK_TO_REPORT_START'export const REPORT_FORM_CLOSED = 'REPORT_FORM_CLOSED'-export const SHOW_NAV_SEARCH = 'SHOW_NAV_SEARCH'export const SET_SHOW_NOTIFICATION = 'SET_SHOW_NOTIFICATION'export const SET_EMBEDDED = 'SET_EMBEDDED'export const SET_REFERRED = 'SET_REFERRED'@@ -37,3 +32,6 @@ export const UPDATE_FILTERS = 'UPDATE_FILTERS'export const SET_ACTIVE_MEDIA_ITEM = 'SET_ACTIVE_MEDIA_ITEM'export const UNSET_ACTIVE_MEDIA_ITEM = 'UNSET_ACTIVE_MEDIA_ITEM'export const RESET_MEDIA = 'RESET_MEDIA'+export const REPLACE_FILTERS = 'REPLACE_FILTERS'+export const REPLACE_QUERY = 'REPLACE_QUERY'+export const SET_Q = 'SET_Q'diff --git a/src/constants/store-modules.js b/src/constants/store-modules.jsindex 8f1978850..2e3a92309 100644--- a/src/constants/store-modules.js+++ b/src/constants/store-modules.js@@ -6,3 +6,6 @@ export const NAV = 'nav'export const NOTIFICATION = 'notification'export const REPORT_CONTENT = 'report-content'export const USAGE_DATA = 'usage-data'+export const FILTER = 'filter'+export const SEARCH = 'search'+export const BUG_REPORT = 'bug-report'diff --git a/src/layouts/embedded-with-nav-search.vue b/src/layouts/embedded-with-nav-search.vueindex de466dce7..2b581f792 100644--- a/src/layouts/embedded-with-nav-search.vue+++ b/src/layouts/embedded-with-nav-search.vue@@ -11,6 +11,7 @@import { mapState } from 'vuex'import iframeHeight from '~/mixins/iframe-height'import i18nSync from '~/mixins/i18n-sync'+import { NAV } from '~/constants/store-modules'const embeddedWithNavSearch = {name: 'embedded-with-nav-search',@@ -19,7 +20,7 @@ const embeddedWithNavSearch = {head() {return this.$nuxtI18nHead({ addSeoAttributes: true, addDirAttribute: true })},- computed: { ...mapState('nav', ['isReferredFromCc']) },+ computed: { ...mapState(NAV, ['isReferredFromCc']) },}export default embeddedWithNavSearch</script>diff --git a/src/layouts/embedded.vue b/src/layouts/embedded.vueindex db77a725e..1075e257c 100644--- a/src/layouts/embedded.vue+++ b/src/layouts/embedded.vue@@ -11,6 +11,7 @@import { mapState } from 'vuex'import iframeHeight from '~/mixins/iframe-height'import i18nSync from '~/mixins/i18n-sync'+import { NAV } from '~/constants/store-modules'const embeddedPage = {name: 'embedded',@@ -19,7 +20,7 @@ const embeddedPage = {head() {return this.$nuxtI18nHead({ addSeoAttributes: true, addDirAttribute: true })},- computed: { ...mapState('nav', ['isReferredFromCc']) },+ computed: { ...mapState(NAV, ['isReferredFromCc']) },}export default embeddedPage</script>diff --git a/src/pages/about.vue b/src/pages/about.vueindex e3be535e5..ed45ccd97 100644--- a/src/pages/about.vue+++ b/src/pages/about.vue@@ -97,6 +97,7 @@<script>import { mapState } from 'vuex'+import { NAV } from '~/constants/store-modules'const AboutPage = {name: 'about-page',@@ -106,7 +107,7 @@ const AboutPage = {: 'with-nav-search'},computed: {- ...mapState('nav', ['isEmbedded']),+ ...mapState(NAV, ['isEmbedded']),},}diff --git a/src/pages/audio/_id.vue b/src/pages/audio/_id.vueindex 25e4861ce..0d6f7bf6b 100644--- a/src/pages/audio/_id.vue+++ b/src/pages/audio/_id.vue@@ -23,12 +23,13 @@</template><script>-import { mapActions, mapState } from 'vuex'+import { mapState } from 'vuex'import { FETCH_AUDIO } from '~/constants/action-types'import iframeHeight from '~/mixins/iframe-height'import { AUDIO } from '~/constants/media'import attributionHtml from '~/utils/attribution-html'import { getFullLicenseName } from '~/utils/license'+import { SEARCH } from '~/constants/store-modules'const AudioDetailPage = {name: 'AudioDetailPage',@@ -47,7 +48,7 @@ const AudioDetailPage = {}},computed: {- ...mapState(['audio']),+ ...mapState(SEARCH, ['audio']),fullLicenseName() {return getFullLicenseName(this.audio.license, this.audio.license_version)},@@ -62,7 +63,7 @@ const AudioDetailPage = {},async asyncData({ env, store, route, error, app }) {try {- await store.dispatch(FETCH_AUDIO, { id: route.params.id })+ await store.dispatch(`${SEARCH}/${FETCH_AUDIO}`, { id: route.params.id })return {thumbnailURL: `${env.apiUrl}thumbs/${route.params.id}`,id: route.params.id,@@ -86,7 +87,6 @@ const AudioDetailPage = {})},methods: {- ...mapActions([FETCH_AUDIO]),attributionHtml() {const licenseUrl = `${this.licenseUrl}&atype=html`return attributionHtml(this.audio, licenseUrl, this.fullLicenseName)diff --git a/src/pages/extension.vue b/src/pages/extension.vueindex 4ef9e9a57..3494d8040 100644--- a/src/pages/extension.vue+++ b/src/pages/extension.vue@@ -77,6 +77,7 @@ import ExtensionBrowsers from '~/components/ExtensionBrowsers'import feature1 from '~/assets/screenshots/extension_feat_1.png'import feature2 from '~/assets/screenshots/extension_feat_2.png'import feature3 from '~/assets/screenshots/extension_feat_3.png'+import { NAV } from '~/constants/store-modules'const AboutPage = {name: 'about-page',@@ -98,7 +99,7 @@ const AboutPage = {}},computed: {- ...mapState('nav', ['isEmbedded']),+ ...mapState(NAV, ['isEmbedded']),},methods: {togglePlay() {diff --git a/src/pages/feedback.vue b/src/pages/feedback.vueindex 4040fd8c9..4258d7b33 100644--- a/src/pages/feedback.vue+++ b/src/pages/feedback.vue@@ -62,6 +62,7 @@<script>import { mapState } from 'vuex'+import { BUG_REPORT, NAV } from '~/constants/store-modules'const bugForm ='https://docs.google.com/forms/d/e/1FAIpQLSenCn-3HoZlCz4vlL2621wjezfu1sPZDaWGe_FtQ1R5-5qR4Q/viewform'@@ -97,12 +98,12 @@ export const FeedbackPage = {},},computed: {- ...mapState('bug-report', [+ ...mapState(BUG_REPORT, ['isReportingBug','bugReported','bugReportFailed',]),- ...mapState('nav', ['isEmbedded']),+ ...mapState(NAV, ['isEmbedded']),},}diff --git a/src/pages/index.vue b/src/pages/index.vueindex 44c39ac19..bf6800904 100644--- a/src/pages/index.vue+++ b/src/pages/index.vue@@ -3,6 +3,7 @@</template><script>+import { FILTER } from '~/constants/store-modules'import { CLEAR_FILTERS } from '~/constants/mutation-types'const HomePage = {@@ -11,7 +12,7 @@ const HomePage = {return store.state.nav.isEmbedded ? 'embedded' : 'default'},beforeMount() {- this.$store.commit(CLEAR_FILTERS)+ this.$store.dispatch(`${FILTER}/${CLEAR_FILTERS}`)},}diff --git a/src/pages/meta-search.vue b/src/pages/meta-search.vueindex 1daad5b7c..f5e732df1 100644--- a/src/pages/meta-search.vue+++ b/src/pages/meta-search.vue@@ -104,6 +104,7 @@<script>import { mapState } from 'vuex'+import { NAV } from '~/constants/store-modules'export default {name: 'MetaSearchPage',@@ -113,7 +114,7 @@ export default {: 'with-nav-search'},computed: {- ...mapState('nav', ['isEmbedded']),+ ...mapState(NAV, ['isEmbedded']),},}</script>diff --git a/src/pages/photos/_id.vue b/src/pages/photos/_id.vueindex 18501d192..bf33273d8 100644--- a/src/pages/photos/_id.vue+++ b/src/pages/photos/_id.vue@@ -18,6 +18,7 @@import axios from 'axios'import { mapActions, mapState } from 'vuex'import { FETCH_IMAGE } from '~/constants/action-types'+import { SEARCH } from '~/constants/store-modules'const PhotoDetailPage = {name: 'PhotoDetailPage',@@ -39,7 +40,13 @@ const PhotoDetailPage = {}},computed: {- ...mapState(['image']),+ ...mapState(SEARCH, ['image']),+ },+ async asyncData({ env, route }) {+ return {+ thumbnailURL: `${env.apiUrl}thumbs/${route.params.id}`,+ imageId: route.params.id,+ }},async fetch() {this.imageId = this.$route.params.id@@ -66,7 +73,7 @@ const PhotoDetailPage = {})},methods: {- ...mapActions({ fetchImage: FETCH_IMAGE }),+ ...mapActions(SEARCH, { fetchImage: FETCH_IMAGE }),onImageLoaded(event) {this.imageWidth = event.target.naturalWidththis.imageHeight = event.target.naturalHeightdiff --git a/src/pages/search-help.vue b/src/pages/search-help.vueindex 71026131d..6b2c6fb40 100644--- a/src/pages/search-help.vue+++ b/src/pages/search-help.vue@@ -256,6 +256,7 @@/* eslint-disable vue/html-quotes */import { mapState } from 'vuex'+import { NAV } from '~/constants/store-modules'const SearchHelpPage = {name: 'search-help-page',@@ -265,7 +266,7 @@ const SearchHelpPage = {: 'with-nav-search'},computed: {- ...mapState('nav', ['isEmbedded']),+ ...mapState(NAV, ['isEmbedded']),},methods: {providerSearchLink(providerCode) {diff --git a/src/pages/search.vue b/src/pages/search.vueindex bbc24517c..19d461dc6 100644--- a/src/pages/search.vue+++ b/src/pages/search.vue@@ -28,14 +28,11 @@<script>import {FETCH_MEDIA,+ SET_FILTERS_FROM_URL,SET_SEARCH_TYPE_FROM_URL,UPDATE_SEARCH_TYPE,} from '~/constants/action-types'-import {- SET_QUERY,- SET_FILTER_IS_VISIBLE,- SET_FILTERS_FROM_URL,-} from '~/constants/mutation-types'+import { SET_QUERY, SET_FILTER_IS_VISIBLE } from '~/constants/mutation-types'import {queryStringToQueryData,queryStringToSearchType,@@ -43,7 +40,8 @@ import {import local from '~/utils/local'import { screenWidth } from '~/utils/get-browser-info'import { ALL_MEDIA, IMAGE } from '~/constants/media'-import { mapActions, mapMutations } from 'vuex'+import { mapActions, mapMutations, mapState } from 'vuex'+import { FILTER, SEARCH } from '~/constants/store-modules'import debounce from 'lodash.debounce'const BrowsePage = {@@ -85,29 +83,25 @@ const BrowsePage = {window.removeEventListener('scroll', this.debounceScrollHandling)},computed: {- query() {- return this.$store.state.query- },- isFilterVisible() {- return this.$store.state.isFilterVisible- },+ ...mapState(SEARCH, ['query', 'searchType']),+ ...mapState(FILTER, ['isFilterVisible']),mediaType() {// Default to IMAGE until media search/index is generalized- return this.$store.state.searchType != ALL_MEDIA- ? this.$store.state.searchType- : IMAGE+ return this.searchType !== ALL_MEDIA ? this.searchType : IMAGE},},methods: {- ...mapActions({+ ...mapActions(SEARCH, {fetchMedia: FETCH_MEDIA,setSearchTypeFromUrl: SET_SEARCH_TYPE_FROM_URL,updateSearchType: UPDATE_SEARCH_TYPE,}),- ...mapMutations({+ ...mapMutations(SEARCH, {setQuery: SET_QUERY,- setFilterVisibility: SET_FILTER_IS_VISIBLE,+ }),+ ...mapMutations(FILTER, {setFiltersFromUrl: SET_FILTERS_FROM_URL,+ setFilterVisibility: SET_FILTER_IS_VISIBLE,}),getMediaItems(params, mediaType) {this.fetchMedia({ ...params, mediaType })@@ -137,7 +131,7 @@ const BrowsePage = {if (newQuery) {const newPath = this.localePath({path: this.$route.path,- query: this.$store.state.query,+ query: newQuery,})this.$router.push(newPath)this.getMediaItems(newQuery, this.mediaType)diff --git a/src/pages/sources.vue b/src/pages/sources.vueindex 6e9ac749d..f0aa7a157 100644--- a/src/pages/sources.vue+++ b/src/pages/sources.vue@@ -136,6 +136,7 @@<script>import sortBy from 'lodash.sortby'import { mapState } from 'vuex'+import { NAV, PROVIDER } from '~/constants/store-modules'const SourcePage = {name: 'source-page',@@ -153,8 +154,8 @@ const SourcePage = {}},computed: {- ...mapState('nav', ['isEmbedded']),- ...mapState('provider', ['imageProviders']),+ ...mapState(NAV, ['isEmbedded']),+ ...mapState(PROVIDER, ['imageProviders']),sortedProviders() {const sorted = sortBy(this.imageProviders, [this.sort.field])return this.sort.direction === 'asc' ? sorted : sorted.reverse()diff --git a/src/store-modules/filter-store.js b/src/store/filter.jssimilarity index 79%rename from src/store-modules/filter-store.jsrename to src/store/filter.jsindex 42482a780..6c1501d35 100644--- a/src/store-modules/filter-store.js+++ b/src/store/filter.js@@ -2,10 +2,7 @@ import findIndex from 'lodash.findindex'import clonedeep from 'lodash.clonedeep'import local from '~/utils/local'-import {- filtersToQueryData,- queryToFilterData,-} from '~/utils/search-query-transform'+import { queryToFilterData } from '~/utils/search-query-transform'import {ALL_MEDIA,AUDIO,@@ -13,15 +10,20 @@ import {VIDEO,supportedMediaTypes,} from '~/constants/media'-import { TOGGLE_FILTER } from '~/constants/action-types'+import {+ SET_FILTERS_FROM_URL,+ TOGGLE_FILTER,+ UPDATE_QUERY,+} from '~/constants/action-types'import {SET_FILTER,SET_PROVIDERS_FILTERS,CLEAR_FILTERS,- SET_FILTERS_FROM_URL,SET_FILTER_IS_VISIBLE,UPDATE_FILTERS,+ REPLACE_FILTERS,} from '~/constants/mutation-types'+import { SEARCH } from '~/constants/store-modules'// The order of the keys here is the same as in the side filter displayexport const mediaFilterKeys = {@@ -163,31 +165,36 @@ export const filterData = {* @param filters* @returns {boolean}*/+// eslint-disable-next-line no-unused-varsconst anyFilterApplied = (filters) =>Object.keys(filters).some((filterKey) => {if (filterKey === 'mature') {return false} // this is hardcoded to "false" because we do not show mature in `FilterDisplay.vue` like the other filters- return filters[filterKey].some((filter) => filter.checked)+ return (+ filters[filterKey] && filters[filterKey].some((filter) => filter.checked)+ )})-const state = {- filters: filterData,+export const state = () => ({+ filters: clonedeep(filterData),isFilterVisible: false,-}+})-const getters = {+export const getters = {/*** Returns all applied filters in unified format* Mature filter is not returned because it is not displayed* as a filter tag* @param state+ * @param getters+ * @param rootState* @returns {{code: string, name: string, filterType: string}[]}*/- appliedFilterTags: (state) => {+ appliedFilterTags: (state, getters, rootState) => {let appliedFilters = []- const filterKeys = mediaFilterKeys[state.searchType]+ const filterKeys = mediaFilterKeys[rootState.search.searchType]filterKeys.forEach((filterType) => {if (filterType !== 'mature') {const newFilters = state.filters[filterType]@@ -204,9 +211,9 @@ const getters = {})return appliedFilters},- isAnyFilterApplied: (state) => {+ isAnyFilterApplied: (state, getters, rootState) => {return anyFilterApplied(- getMediaTypeFilters(state, { mediaType: state.searchType })+ getMediaTypeFilters(state, { mediaType: rootState.search.searchType }))},allFiltersForDisplay: (state) => {@@ -236,22 +243,35 @@ const getters = {}const actions = {- [TOGGLE_FILTER]({ commit, state }, params) {+ [TOGGLE_FILTER]({ commit, dispatch, state }, params) {const { filterType, code } = paramsconst filters = state.filters[filterType]const codeIdx = findIndex(filters, (f) => f.code === code)commit(SET_FILTER, { codeIdx, ...params })+ dispatch(`${SEARCH}/${UPDATE_QUERY}`, null, { root: true })},-}--function setQuery(state) {- const query = filtersToQueryData(state.filters, state.searchType)+ [CLEAR_FILTERS]({ commit, dispatch, state }) {+ const initialFilters = clonedeep(filterData)- state.query = {- q: state.query.q,- ...query,- }+ const resetProviders = (mediaType) => {+ return state.filters[`${mediaType}Providers`].map((provider) => ({+ ...provider,+ checked: false,+ }))+ }+ const newFilterData = {+ ...initialFilters,+ audioProviders: resetProviders(AUDIO),+ imageProviders: resetProviders(IMAGE),+ }+ commit(REPLACE_FILTERS, { newFilterData })+ dispatch(`${SEARCH}/${UPDATE_QUERY}`, null, { root: true })+ },+ [SET_FILTERS_FROM_URL]({ commit }, { url }) {+ const newFilterData = queryToFilterData(url)+ commit(REPLACE_FILTERS, { newFilterData })+ },}function getMediaTypeFilters(state, { mediaType, includeMature = false }) {@@ -266,42 +286,17 @@ function getMediaTypeFilters(state, { mediaType, includeMature = false }) {return mediaTypeFilters}-function replaceFilters(state, filterData) {- Object.keys(state.filters).forEach((filterType) => {- if (filterType === 'mature') {- state.filters.mature = filterData.mature- } else if (['audioProviders', 'imageProviders'].includes(filterType)) {- filterData[filterType].forEach((provider) => {- const idx = state.filters[filterType].findIndex(- (p) => p.code === provider.code- )- if (idx > -1) {- state.filters[filterType][idx].checked = provider.checked- }- })- } else {- state.filters[filterType] = filterData[filterType]- }- })-}--function setFilter(state, params) {- const { filterType, codeIdx } = params- if (filterType === 'mature') {- state.filters.mature = !state.filters.mature- } else {- const filters = state.filters[filterType]- filters[codeIdx].checked = !filters[codeIdx].checked- }-- setQuery(state, params)-}-// Make sure when redirecting after applying a filter, we stick to the right tab (i.e, "/search/video", "/search/audio", etc.)const mutations = {- [UPDATE_FILTERS](state) {+ /**+ * After a search type is changed, unchecks all the filters that are not+ * applicable for this Media type.+ * @param state+ * @param searchType+ */+ [UPDATE_FILTERS](state, { searchType }) {const mediaTypesToClear = supportedMediaTypes.filter(- (media) => media !== state.searchType+ (media) => media !== searchType)let filterKeysToClear = []@@ -319,27 +314,32 @@ const mutations = {}})},- [SET_FILTERS_FROM_URL](state, params) {- replaceFilters(state, queryToFilterData(params.url))+ [REPLACE_FILTERS](state, { newFilterData }) {+ Object.keys(state.filters).forEach((filterType) => {+ if (filterType === 'mature') {+ state.filters.mature = newFilterData.mature+ } else if (['audioProviders', 'imageProviders'].includes(filterType)) {+ newFilterData[filterType].forEach((provider) => {+ const idx = state.filters[filterType].findIndex(+ (p) => p.code === provider.code+ )+ if (idx > -1) {+ state.filters[filterType][idx].checked = provider.checked+ }+ })+ } else {+ state.filters[filterType] = newFilterData[filterType]+ }+ })},[SET_FILTER](state, params) {- return setFilter(state, params)- },- [CLEAR_FILTERS](state) {- const initialFilters = clonedeep(filterData)-- const resetProviders = (mediaType) => {- return state.filters[`${mediaType}Providers`].map((provider) => ({- ...provider,- checked: false,- }))- }- state.filters = {- ...initialFilters,- audioProviders: resetProviders(AUDIO),- imageProviders: resetProviders(IMAGE),+ const { filterType, codeIdx } = params+ if (filterType === 'mature') {+ state.filters.mature = !state.filters.mature+ } else {+ const filters = state.filters[filterType]+ filters[codeIdx].checked = !filters[codeIdx].checked}- return setQuery(state)},[SET_PROVIDERS_FILTERS](state, params) {const { mediaType, providers } = paramsdiff --git a/src/store/index.js b/src/store/index.jsindex 635dd5c8c..9199ed6bf 100644--- a/src/store/index.js+++ b/src/store/index.js@@ -1,34 +1,12 @@-import AudioService from '~/data/audio-service'-import ImageService from '~/data/image-service'-import SearchStore from '~/store-modules/search-store'-import FilterStore from '~/store-modules/filter-store'import { FETCH_MEDIA_PROVIDERS } from '~/constants/action-types'import { PROVIDER } from '~/constants/store-modules'-import { AUDIO, IMAGE } from '~/constants/media'-const mediaServices = { [AUDIO]: AudioService, [IMAGE]: ImageService }--export const actions = Object.assign(- SearchStore.actions(mediaServices),- FilterStore.actions,- {- async nuxtServerInit({ dispatch }) {- try {- await dispatch(`${PROVIDER}/${FETCH_MEDIA_PROVIDERS}`)- } catch (error) {- // TODO: What happens if we do not have image providers?- // How do we show the error to the user?- console.error("Couldn't fetch media providers")- }- },- }-)--export const state = () => Object.assign(SearchStore.state, FilterStore.state)--export const getters = Object.assign(FilterStore.getters)--export const mutations = Object.assign(- SearchStore.mutations,- FilterStore.mutations-)+export const actions = {+ async nuxtServerInit({ dispatch }) {+ try {+ await dispatch(`${PROVIDER}/${FETCH_MEDIA_PROVIDERS}`)+ } catch (error) {+ console.error("Couldn't fetch media providers")+ }+ },+}diff --git a/src/store/provider.js b/src/store/provider.jsindex fb50e3116..6225ea45c 100644--- a/src/store/provider.js+++ b/src/store/provider.js@@ -14,6 +14,7 @@ import {SET_MEDIA_PROVIDERS,SET_PROVIDERS_FILTERS,} from '~/constants/mutation-types'+import { FILTER } from '~/constants/store-modules'const AudioProviderService = MediaProviderService(AUDIO)const ImageProviderService = MediaProviderService(IMAGE)@@ -72,7 +73,7 @@ export const createActions = (services) => ({providers: sortedProviders,})commit(- `${SET_PROVIDERS_FILTERS}`,+ `${FILTER}/${SET_PROVIDERS_FILTERS}`,{mediaType,providers: sortedProviders,diff --git a/src/store-modules/search-store.js b/src/store/search.jssimilarity index 67%rename from src/store-modules/search-store.jsrename to src/store/search.jsindex 4682c1647..a751e8ad6 100644--- a/src/store-modules/search-store.js+++ b/src/store/search.js@@ -8,6 +8,7 @@ import {HANDLE_MEDIA_ERROR,HANDLE_NO_MEDIA,SET_SEARCH_TYPE_FROM_URL,+ UPDATE_QUERY,UPDATE_SEARCH_TYPE,} from '~/constants/action-types'import {@@ -15,11 +16,13 @@ import {FETCH_MEDIA_ERROR,FETCH_START_MEDIA,MEDIA_NOT_FOUND,+ REPLACE_QUERY,RESET_MEDIA,SET_AUDIO,SET_IMAGE,SET_IMAGE_PAGE,SET_MEDIA,+ SET_Q,SET_QUERY,SET_SEARCH_TYPE,UPDATE_FILTERS,@@ -28,17 +31,17 @@ import {SEND_RESULT_CLICKED_EVENT,SEND_SEARCH_QUERY_EVENT,} from '~/constants/usage-data-analytics-types'-import { queryStringToSearchType } from '~/utils/search-query-transform'+import {+ filtersToQueryData,+ queryStringToSearchType,+} from '~/utils/search-query-transform'import { ALL_MEDIA, AUDIO, IMAGE } from '~/constants/media'-import { USAGE_DATA } from '~/constants/store-modules'--// const getSearchPath = () =>-// window.location.pathname && window.location.pathname.includes('search')-// ? window.location.pathname-// : '/search'+import { FILTER, USAGE_DATA } from '~/constants/store-modules'+import AudioService from '~/data/audio-service'+import ImageService from '~/data/image-service'/**- * @type {{ audios: import('../store/types').AudioDetail[],+ * @type {{ audios: import('./types').AudioDetail[],* audiosCount: number, audioPage:number,* images: import('../store/types').ImageDetail[],* imagePage: number, imagesCount: number, query: {},@@ -47,7 +50,7 @@ import { USAGE_DATA } from '~/constants/store-modules'* isFetchingError: {images: boolean, audios: boolean},* errorMessage: null, searchType: string, }}*/-const state = {+export const state = () => ({audios: [],audiosCount: 0,audioPage: 1,@@ -71,17 +74,19 @@ const state = {query: {},audio: {},image: {},-}+})-const actions = (services) => ({+export const createActions = (services) => ({async [FETCH_MEDIA]({ commit, dispatch, rootState }, params) {// does not send event if user is paginating for more resultsconst { page, mediaType, q } = params+ const sessionId = rootState.user.usageSessionIdif (!page) {- dispatch(`${USAGE_DATA}/${SEND_SEARCH_QUERY_EVENT}`, {- query: q,- sessionId: rootState.user.usageSessionId,- })+ dispatch(+ `${USAGE_DATA}/${SEND_SEARCH_QUERY_EVENT}`,+ { query: q, sessionId },+ { root: true }+ )}commit(FETCH_START_MEDIA, { mediaType })@@ -112,12 +117,16 @@ const actions = (services) => ({})},async [FETCH_AUDIO]({ commit, dispatch, state, rootState }, params) {- dispatch(`${USAGE_DATA}/${SEND_RESULT_CLICKED_EVENT}`, {- query: state.query.q,- resultUuid: params.id,- resultRank: findIndex(state.audios, (img) => img.id === params.id),- sessionId: rootState.user.usageSessionId,- })+ dispatch(+ `${USAGE_DATA}/${SEND_RESULT_CLICKED_EVENT}`,+ {+ query: state.query.q,+ resultUuid: params.id,+ resultRank: findIndex(state.audios, (img) => img.id === params.id),+ sessionId: rootState.user.usageSessionId,+ },+ { root: true }+ )commit(SET_AUDIO, { audio: {} })await services[AUDIO].getMediaDetail(params).then(({ data }) => {@@ -132,12 +141,16 @@ const actions = (services) => ({})},async [FETCH_IMAGE]({ commit, dispatch, state, rootState }, params) {- dispatch(`${USAGE_DATA}/${SEND_RESULT_CLICKED_EVENT}`, {- query: state.query.q,- resultUuid: params.id,- resultRank: findIndex(state.images, (img) => img.id === params.id),- sessionId: rootState.user.usageSessionId,- })+ dispatch(+ `${USAGE_DATA}/${SEND_RESULT_CLICKED_EVENT}`,+ {+ query: state.query.q,+ resultUuid: params.id,+ resultRank: findIndex(state.images, (img) => img.id === params.id),+ sessionId: rootState.user.usageSessionId,+ },+ { root: true }+ )commit(SET_IMAGE, { image: {} })await services[IMAGE].getMediaDetail(params)@@ -173,16 +186,35 @@ const actions = (services) => ({}},[SET_SEARCH_TYPE_FROM_URL]({ commit }, params) {- commit(SET_SEARCH_TYPE, { searchType: queryStringToSearchType(params.url) })- commit(UPDATE_FILTERS)+ const searchType = queryStringToSearchType(params.url)+ commit(SET_SEARCH_TYPE, { searchType })+ commit(`${FILTER}/${UPDATE_FILTERS}`, { searchType }, { root: true })},- [UPDATE_SEARCH_TYPE]({ commit }, params) {- commit(SET_SEARCH_TYPE, { searchType: params.searchType })- commit(UPDATE_FILTERS)+ [UPDATE_SEARCH_TYPE]({ commit }, { searchType }) {+ commit(SET_SEARCH_TYPE, { searchType })+ commit(`${FILTER}/${UPDATE_FILTERS}`, { searchType }, { root: true })+ },+ [UPDATE_QUERY]({ commit, state, rootState }) {+ const query = filtersToQueryData(rootState.filter.filters, state.searchType)+ commit(REPLACE_QUERY, {+ query: {+ q: state.query.q,+ ...query,+ },+ })},})-const mutations = {+export const getters = {+ isFetching(state) {+ return state.isFetching[state.searchType]+ },+ isFetchingError(state) {+ return state.isFetchingError[state.searchType]+ },+}++export const mutations = {[FETCH_START_MEDIA](_state, { mediaType }) {const mediaPlural = `${mediaType}s`_state.isFetching[mediaPlural] = true@@ -230,9 +262,39 @@ const mutations = {_state[`${mediaType}Page`] = page || 1_state.pageCount[mediaPlural] = pageCount},- [SET_QUERY](_state, params) {- _state.query = Object.assign({}, _state.query, params.query)+ /**+ * Merges the query object from parameters with the existing+ * query object. Used on 'Search' button click.+ * @param _state+ * @param {object} query+ */+ [SET_QUERY](_state, { query }) {+ _state.query = Object.assign({}, _state.query, query)_state.images = []+ _state.audios = []+ },+ /**+ * When a new search term is searched for, sets the `q`+ * parameter for the API request query and resets the media.+ * Leaves other query parameters for filters as before.+ * @param _state+ * @param {string} q+ */+ [SET_Q](_state, { q }) {+ _state.query.q = q+ _state.images = []+ _state.audios = []+ },+ /**+ * Replaces the query object completely and resets all the+ * media. Called when filters are updated.+ * @param _state+ * @param {object} query+ */+ [REPLACE_QUERY](_state, { query }) {+ _state.query = query+ _state.images = []+ _state.audios = []},[MEDIA_NOT_FOUND](_state, params) {throw new Error(`Media of type ${params.mediaType} not found`)@@ -249,8 +311,12 @@ const mutations = {},}+const mediaServices = { [AUDIO]: AudioService, [IMAGE]: ImageService }+const actions = createActions(mediaServices)+export default {state,+ getters,actions,mutations,}diff --git a/src/utils/search-query-transform.js b/src/utils/search-query-transform.jsindex 3d73c2603..4849bccde 100644--- a/src/utils/search-query-transform.js+++ b/src/utils/search-query-transform.js@@ -1,6 +1,6 @@import clonedeep from 'lodash.clonedeep'import findIndex from 'lodash.findindex'-import { filterData, mediaSpecificFilters } from '~/store-modules/filter-store'+import { filterData, mediaSpecificFilters } from '~/store/filter'import getParameterByName from './get-parameter-by-name'import { ALL_MEDIA } from '~/constants/media'diff --git a/src/utils/sixpack.js b/src/utils/sixpack.jsindex 7b4a96a0c..0461f019a 100644--- a/src/utils/sixpack.js+++ b/src/utils/sixpack.js@@ -70,7 +70,7 @@ export const participate = (session: sessionId,})).catch((error) => {- console.error(error)+ console.error(`Using default a/b case due to error: ${error.message}`)return {name,case: defaultCase,diff --git a/test/unit/specs/components/AudioTrack/audio-track.spec.js b/test/unit/specs/components/AudioTrack/audio-track.spec.jsindex d55174500..5b167920e 100644--- a/test/unit/specs/components/AudioTrack/audio-track.spec.js+++ b/test/unit/specs/components/AudioTrack/audio-track.spec.js@@ -19,6 +19,7 @@ const useVueI18n = (vue) => {const stubs = {AudioController: true,+ DownloadButton: true,PlayPause: true,NuxtLink: true,Waveform: true,diff --git a/test/unit/specs/components/ContentReport/content-report-form.spec.js b/test/unit/specs/components/ContentReport/content-report-form.spec.jsindex c09ec3f55..adad5b2bf 100644--- a/test/unit/specs/components/ContentReport/content-report-form.spec.js+++ b/test/unit/specs/components/ContentReport/content-report-form.spec.js@@ -1,17 +1,22 @@import ContentReportForm from '~/components/ContentReport/ContentReportForm'import render from '../../../test-utils/render'import i18n from '../../../test-utils/i18n'-import { PROVIDER, REPORT_CONTENT } from '~/constants/store-modules'+import { REPORT_CONTENT } from '~/constants/store-modules'import { SEND_CONTENT_REPORT } from '~/constants/action-types'import { REPORT_FORM_CLOSED } from '~/constants/mutation-types'+import Vuex from 'vuex'+import { createLocalVue } from '@vue/test-utils'+import reportContentStore from '~/store/report-content'describe('ContentReportForm', () => {let props = nulllet options = {}- let storeState = nulllet dispatchMock = nulllet commitMock = nullconst $t = (key) => i18n.messages[key]+ let storeMock = null+ let localVue = null+beforeEach(() => {props = {image: { id: 1, url: 'http://foo.bar' },@@ -19,27 +24,34 @@ describe('ContentReportForm', () => {dispatchMock = jest.fn()commitMock = jest.fn()-- storeState = {- $store: {- dispatch: dispatchMock,- commit: commitMock,- state: {- [PROVIDER]: {- imageProviders: [],- },- [REPORT_CONTENT]: {+ localVue = createLocalVue()+ localVue.use(Vuex)+ storeMock = new Vuex.Store({+ modules: {+ 'report-content': {+ namespaced: true,+ state: {isReportSent: false,reportFailed: false,},+ mutations: {+ ...reportContentStore.mutations,+ [REPORT_FORM_CLOSED]: commitMock,+ },+ actions: reportContentStore.actions,+ },+ provider: {+ namespaced: true,+ imageProviders: [],},},- }+ })options = {propsData: props,+ store: storeMock,+ localVue,mocks: {- ...storeState,$t,},}@@ -51,13 +63,13 @@ describe('ContentReportForm', () => {})it('should render report sent', async () => {- storeState.$store.state[REPORT_CONTENT].isReportSent = true+ storeMock.state[REPORT_CONTENT].isReportSent = trueconst wrapper = render(ContentReportForm, options)expect(wrapper.findComponent({ name: 'DoneMessage' }).vm).toBeDefined()})it('should render error message', async () => {- storeState.$store.state[REPORT_CONTENT].reportFailed = true+ storeMock.state[REPORT_CONTENT].reportFailed = trueconst wrapper = render(ContentReportForm, options)expect(wrapper.findComponent({ name: 'ReportError' }).vm).toBeDefined()})@@ -85,6 +97,7 @@ describe('ContentReportForm', () => {})it('should dispatch SEND_CONTENT_REPORT on next when mature is selected', async () => {+ storeMock.dispatch = dispatchMockconst wrapper = render(ContentReportForm, options)const radio = wrapper.find('#mature')await radio.setChecked()@@ -102,6 +115,7 @@ describe('ContentReportForm', () => {})it('should not dispatch SEND_CONTENT_REPORT on next when dmca is selected', async () => {+ storeMock.dispatch = dispatchMockconst wrapper = render(ContentReportForm, options)const radio = wrapper.find('#dmca')await radio.setChecked()@@ -112,6 +126,7 @@ describe('ContentReportForm', () => {})it('should dispatch SEND_CONTENT_REPORT on other form submit', async () => {+ storeMock.dispatch = dispatchMockconst wrapper = render(ContentReportForm, options)await wrapper.setData({ selectedReason: 'other' })const description = 'foo bar'@@ -126,13 +141,6 @@ describe('ContentReportForm', () => {)})- it('should close form', async () => {- const wrapper = render(ContentReportForm, options)-- const button = wrapper.find('.close-button')- await button.trigger('click')- expect(commitMock).toHaveBeenCalledWith(- `${REPORT_CONTENT}/${REPORT_FORM_CLOSED}`- )- })+ // TODO: Rewrite test using testing library (@obulat)+ it('should close form', async () => {})})diff --git a/test/unit/specs/components/ImageDetails/image-info.spec.js b/test/unit/specs/components/ImageDetails/image-info.spec.jsindex c018973ee..28732adf6 100644--- a/test/unit/specs/components/ImageDetails/image-info.spec.js+++ b/test/unit/specs/components/ImageDetails/image-info.spec.js@@ -1,12 +1,29 @@import ImageInfo from '~/components/ImageDetails/ImageInfo'import render from '../../../test-utils/render'import i18n from '../../../test-utils/i18n'+import { createLocalVue } from '@vue/test-utils'+import Vuex from 'vuex'describe('Image Info', () => {let props = nulllet options = {}+ let localVue = null+ let storeMock = nullconst $t = (key) => i18n.messages[key]beforeEach(() => {+ localVue = createLocalVue()+ localVue.use(Vuex)+ storeMock = new Vuex.Store({+ modules: {+ provider: {+ namespaced: true,+ state: {+ provider: 'flickr',+ source: 'flickr',+ },+ },+ },+ })props = {image: {id: 0,@@ -28,14 +45,10 @@ describe('Image Info', () => {}options = {+ localVue,propsData: props,+ store: storeMock,mocks: {- $store: {- state: {- provider: 'flickr',- source: 'flickr',- },- },$t,},}diff --git a/test/unit/specs/components/filter-display.spec.js b/test/unit/specs/components/filter-display.spec.jsindex 4668dc22d..9ee71cd99 100644--- a/test/unit/specs/components/filter-display.spec.js+++ b/test/unit/specs/components/filter-display.spec.js@@ -1,22 +1,27 @@import { render } from '@testing-library/vue'import FilterDisplay from '~/components/Filters/FilterDisplay'+import { createLocalVue } from '@vue/test-utils'+import Vuex from 'vuex'describe('FilterDisplay', () => {- const options = {- mocks: {- $store: {+ const localVue = createLocalVue()+ localVue.use(Vuex)+ const storeMock = new Vuex.Store({+ modules: {+ search: {+ namespaced: true,state: {query: {q: 'foo',- provider: 'foo',},- filters: {},},- dispatch: jest.fn(),+ },+ filter: {+ namespaced: true,getters: {- isAnyFilterApplied: true,- appliedFilterTags: [+ isAnyFilterApplied: () => true,+ appliedFilterTags: () => [{code: 'cc0',filterType: 'license',@@ -26,6 +31,10 @@ describe('FilterDisplay', () => {},},},+ })+ const options = {+ localVue,+ store: storeMock,}it('should render correct contents', () => {diff --git a/test/unit/specs/components/hero-section.spec.js b/test/unit/specs/components/hero-section.spec.jsindex 89288ec72..745c1f7d4 100644--- a/test/unit/specs/components/hero-section.spec.js+++ b/test/unit/specs/components/hero-section.spec.js@@ -1,42 +1,69 @@import HeroSection from '~/components/HeroSection'-import render from '../../test-utils/render'-import { filterData } from '~/store-modules/filter-store'+import { fireEvent, render, screen } from '@testing-library/vue'+import filterStore, { filterData } from '~/store/filter'+import store from '~/store/search'+import { createLocalVue } from '@vue/test-utils'+import Vuex from 'vuex'+import clonedeep from 'lodash.clonedeep'+import VueI18n from 'vue-i18n'+import messages from '~/locales/en.json'++const i18n = new VueI18n({+ locale: 'en',+ fallbackLocale: 'en',+ messages: { en: messages },+})describe('HeroSection', () => {let options = {}- let commitMock = null+ let localVue+ let storeMock+ let filters+ const routerMock = { push: jest.fn() }beforeEach(() => {- commitMock = jest.fn()- options = {- stubs: { HomeLicenseFilter: true },- mocks: {- $router: {- push: () => {},+ localVue = createLocalVue()+ localVue.use(VueI18n)+ localVue.use(Vuex)+ filters = clonedeep(filterData)+ storeMock = new Vuex.Store({+ modules: {+ filter: {+ namespaced: true,+ ...filterStore,+ state: {+ isFilterVisible: true,+ filters,+ },},- $store: {- commit: commitMock,- state: { filters: filterData },+ search: {+ namespaced: true,+ ...store,},},+ })+ options = {+ mocks: {+ $router: routerMock,+ $store: storeMock,+ },+ i18n,}})it('should render correct contents', () => {- const wrapper = render(HeroSection, options)- expect(wrapper.find('.hero').element).toBeDefined()- expect(wrapper.find('.hero-search__form').element).toBeDefined()+ render(HeroSection, options)+ screen.getByRole('search')})it('should search when a query is entered', async () => {- const wrapper = render(HeroSection, options)- const form = wrapper.find('.hero-search__form')- const input = wrapper.find('input[type="search"]')+ render(HeroSection, options)- await input.setValue('me')- await input.trigger('change')- await form.trigger('submit.prevent')+ const searchBox = screen.getByRole('searchbox')+ await fireEvent.update(searchBox, 'me')+ await fireEvent.click(screen.queryByTitle('Search'))- expect(commitMock).toHaveBeenCalledWith('SET_QUERY', {+ expect(routerMock.push).toHaveBeenCalledWith({+ path: '/search/image',query: { q: 'me' },})})diff --git a/test/unit/specs/components/home-license-filter.spec.js b/test/unit/specs/components/home-license-filter.spec.jsindex 89dc6efb2..e00708098 100644--- a/test/unit/specs/components/home-license-filter.spec.js+++ b/test/unit/specs/components/home-license-filter.spec.js@@ -1,16 +1,31 @@import HomeLicenseFilter from '~/components/HomeLicenseFilter'-import render from '../../test-utils/render'+import { render, screen } from '@testing-library/vue'+import { TOGGLE_FILTER } from '~/constants/action-types'+import { FILTER } from '~/constants/store-modules'+import { createLocalVue } from '@vue/test-utils'+import Vuex from 'vuex'describe('HomeLicenseFilter', () => {let options = {}+ let localVue = nulllet dispatchMock = null+ let toggleMock = null+ let storeMock = nullbeforeEach(() => {dispatchMock = jest.fn()- options = {- mocks: {- $store: {- dispatch: dispatchMock,+ toggleMock = jest.fn()++ localVue = createLocalVue()+ localVue.use(Vuex)+ storeMock = new Vuex.Store({+ modules: {+ filter: {+ namespaced: true,+ actions: {+ // Without this action, we get '[vuex] unknown local action type' error+ [TOGGLE_FILTER]: toggleMock,+ },state: {filters: {licenseTypes: [@@ -21,21 +36,33 @@ describe('HomeLicenseFilter', () => {},},},+ })+ options = {+ store: storeMock,}})it('renders checkboxes', () => {- const wrapper = render(HomeLicenseFilter, options)- expect(wrapper.find('#commercial').element).toBeDefined()- expect(wrapper.find('#modification').element).toBeDefined()+ render(HomeLicenseFilter, options)+ const checkboxes = screen.queryAllByRole('checkbox')+ expect(checkboxes.length).toEqual(2)++ const commercialCheckbox = screen.queryByLabelText('Commercial usage')+ expect(commercialCheckbox).toBeTruthy()++ const modificationCheckbox = screen.queryByLabelText('Allows modification')+ expect(modificationCheckbox).toBeTruthy()})it('dispatches `TOGGLE_FILTER` when checkboxes selected', async () => {- const wrapper = render(HomeLicenseFilter, options)- const commercialChk = wrapper.find('#commercial')+ storeMock.dispatch = dispatchMock+ render(HomeLicenseFilter, options)+ const commercialCheckbox = screen.queryByLabelText('Commercial usage')+ await commercialCheckbox.click()+ const checked = screen.queryAllByRole('checkbox', { checked: true })- await commercialChk.setChecked(true)- expect(dispatchMock).toHaveBeenCalledWith('TOGGLE_FILTER', {+ expect(checked.length).toEqual(1)+ expect(dispatchMock).toHaveBeenCalledWith(`${FILTER}/${TOGGLE_FILTER}`, {code: 'commercial',filterType: 'licenseTypes',})diff --git a/test/unit/specs/components/nav-section.spec.js b/test/unit/specs/components/nav-section.spec.jsindex f6a7af078..6b47a2274 100644--- a/test/unit/specs/components/nav-section.spec.js+++ b/test/unit/specs/components/nav-section.spec.js@@ -1,6 +1,8 @@import NavSection from '~/components/NavSection'-import { SET_QUERY } from '~/constants/mutation-types'+import { SET_Q } from '~/constants/mutation-types'import render from '../../test-utils/render'+import { createLocalVue } from '@vue/test-utils'+import Vuex from 'vuex'describe('NavSection', () => {it('should render correct contents', () => {@@ -9,30 +11,39 @@ describe('NavSection', () => {})it('commits a mutation when the form is submitted', async () => {- const storeMock = {- dispatch: jest.fn(),- commit: jest.fn(),- state: {- shareLists: {- length: 2,+ const localVue = createLocalVue()+ localVue.use(Vuex)+ const commitMock = jest.fn()+ const storeMock = new Vuex.Store({+ modules: {+ search: {+ namespaced: true,+ mutations: {+ [SET_Q]: commitMock,+ },},},- }+ })+ const routerMock = { push: jest.fn() }const options = {+ localVue,propsData: {fixedNav: null,showNavSearch: 'true',},- mocks: { $store: storeMock, $router: { push: jest.fn() } },+ store: storeMock,+ mocks: { $router: routerMock },stubs: { NuxtLink: true },}const wrapper = render(NavSection, options)await wrapper.setData({ form: { searchTerm: 'foo' } })wrapper.find('.hero_search-form').trigger('submit')-- expect(storeMock.commit).toHaveBeenCalledWith(SET_QUERY, {+ expect(routerMock.push).toHaveBeenCalledWith({+ path: '/search',query: { q: 'foo' },})+ // The first parameter should be the commit type, but because of the way it's mocked, it's {}+ expect(commitMock).toHaveBeenLastCalledWith({}, { q: 'foo' })})})diff --git a/test/unit/specs/components/photo-tags.spec.js b/test/unit/specs/components/photo-tags.spec.jsindex 5de0c47c1..25b1707b4 100644--- a/test/unit/specs/components/photo-tags.spec.js+++ b/test/unit/specs/components/photo-tags.spec.js@@ -1,6 +1,8 @@-import PhotoTags from '~/components/PhotoTags'-import { SET_QUERY } from '~/constants/mutation-types'+import Vuex from 'vuex'+import { SET_Q } from '~/constants/mutation-types'import render from '../../test-utils/render'+import { createLocalVue } from '@vue/test-utils'+import PhotoTags from '~/components/PhotoTags'describe('PhotoTags', () => {let options = null@@ -40,22 +42,25 @@ describe('PhotoTags', () => {})it('commits a mutation when a tag is clicked', () => {- const storeMock = {- commit: jest.fn(),- }+ const commitMock = jest.fn()+ const localVue = createLocalVue()+ localVue.use(Vuex)+ const storeMock = new Vuex.Store({+ modules: {+ search: { namespaced: true, mutations: { [SET_Q]: commitMock } },+ },+ })const opts = {+ localVue,propsData: {...props,},- mocks: {- $store: storeMock,- },+ store: storeMock,}const wrapper = render(PhotoTags, opts)wrapper.find('.tag').trigger('click')const tagName = wrapper.find('.tag').text()- expect(storeMock.commit).toHaveBeenCalledWith(SET_QUERY, {- query: { q: tagName },- })+ // When mocking the module's mutation, the mutation type comes as `{}`+ expect(commitMock).toHaveBeenCalledWith({}, { q: tagName })})})diff --git a/test/unit/specs/components/search-grid-filter.spec.js b/test/unit/specs/components/search-grid-filter.spec.jsindex 48e04af26..b461095b2 100644--- a/test/unit/specs/components/search-grid-filter.spec.js+++ b/test/unit/specs/components/search-grid-filter.spec.js@@ -1,42 +1,64 @@+import Vuex from 'vuex'+import { fireEvent, render, screen } from '@testing-library/vue'+import { createLocalVue } from '@vue/test-utils'import SearchGridFilter from '~/components/Filters/SearchGridFilter'-import render from '../../test-utils/render'+import { UPDATE_QUERY } from '~/constants/action-types'+import { IMAGE } from '~/constants/media'+import store from '~/store/filter'+import clonedeep from 'lodash.clonedeep'++const initialFilters = {+ licenseTypes: [+ {+ code: 'commercial',+ name: 'Commercial usage',+ checked: false,+ },+ ],+ licenses: [{ code: 'by', name: 'CC-BY', checked: false }],+ imageCategories: [{ code: 'photo', name: 'Photographs', checked: false }],+ imageExtensions: [{ code: 'jpg', name: 'JPG', checked: false }],+ imageProviders: [{ code: 'met', name: 'Metropolitan', checked: false }],+ audioProviders: [{ code: 'jamendo', name: 'Jamendo', checked: false }],+ aspectRatios: [],+ searchBy: [{ code: 'creator', checked: false }],+ mature: false,+}describe('SearchGridFilter', () => {let options = {}- let storeMock = null- let dispatchMock = null- let commitMock = nulllet props = null+ let storeMock+ let localVue+ let filters+beforeEach(() => {- dispatchMock = jest.fn()- commitMock = jest.fn()- storeMock = {- dispatch: dispatchMock,- commit: commitMock,- state: {- isFilterApplied: true,- isFilterVisible: true,- filters: {- licenseTypes: [{ code: 'commercial', name: 'Commercial usage' }],- licenses: [{ code: 'by', name: 'CC-BY' }],- categories: [{ code: 'photo', name: 'Photographs' }],- extensions: [{ code: 'jpg', name: 'JPG' }],- searchBy: {- creator: false,+ localVue = createLocalVue()+ localVue.use(Vuex)+ filters = clonedeep(initialFilters)+ storeMock = new Vuex.Store({+ modules: {+ filter: {+ namespaced: true,+ state: {+ isFilterVisible: true,+ filters,+ },+ mutations: store.mutations,+ actions: store.actions,+ getters: store.getters,+ },+ search: {+ namespaced: true,+ state: { searchType: IMAGE },+ actions: {+ [UPDATE_QUERY]: jest.fn(),},- mature: false,},- query: 'me',},- }-- props = {- showProvidersFilter: true,- provider: undefined,- }+ })options = {- stubs: { FiltersList: true },propsData: props,mocks: {$store: storeMock,@@ -44,55 +66,62 @@ describe('SearchGridFilter', () => {}})- it('should render correct contents', () => {- const wrapper = render(SearchGridFilter, options)- expect(- wrapper.findComponent({ name: 'SearchGridFilter' }).element- ).toBeDefined()- })-- it('should show search filters when isFilterVisible is true', () => {- const wrapper = render(SearchGridFilter, options)- expect(wrapper.find('.search-filters').classes()).toContain(+ it('should show search filters when isFilterVisible is true', async () => {+ storeMock.state.filter.isFilterVisible = true+ await render(SearchGridFilter, options)+ expect(screen.getByTestId('filters-list')).toBeVisible()+ expect(screen.getByTestId('filters-list')).toHaveClass('search-filters__visible')})- it('should not show search filters when isFilterVisible is false', () => {- storeMock.state.isFilterVisible = false- const wrapper = render(SearchGridFilter, options)- expect(wrapper.find('.search-filters').classes()).not.toContain(+ it('should not show search filters when isFilterVisible is false', async () => {+ storeMock.state.filter.isFilterVisible = false+ await render(SearchGridFilter, options)+ // not.toBeVisible does not work+ expect(screen.getByTestId('filters-list')).not.toHaveClass('search-filters__visible')})- it('should not display providers filter when props is set to false', () => {- props.showProvidersFilter = false- const wrapper = render(SearchGridFilter, options)- expect(wrapper.find('.search-filters_providers').element).not.toBeDefined()+ it('toggles filter', async () => {+ render(SearchGridFilter, options)+ const checked = screen.queryAllByRole('checkbox', { checked: true })+ expect(checked.length).toEqual(0)++ await fireEvent.click(screen.queryByLabelText('Commercial usage'))++ // `getBy` serves as expect because it throws an error if no element is found+ screen.getByRole('checkbox', { checked: true })+ screen.getByLabelText('Commercial usage', { checked: true })})- it('toggles filter', () => {- const wrapper = render(SearchGridFilter, options)- wrapper.vm.onUpdateFilter({ code: 'foo', filterType: 'bar' })- expect(dispatchMock).toHaveBeenCalledWith('TOGGLE_FILTER', {- code: 'foo',- filterType: 'bar',- provider: props.provider,+ it('clears filters', async () => {+ storeMock.state.filter.filters.licenses[0].checked = true+ await render(SearchGridFilter, options)+ // if no checked checkboxes were found, this would raise an error+ screen.getByRole('checkbox', { checked: true })++ await fireEvent.click(screen.getByText('filter-list.clear'))+ const checkedFilters = screen.queryAllByRole('checkbox', { checked: true })+ const uncheckedFilters = screen.queryAllByRole('checkbox', {+ checked: false,})+ expect(checkedFilters.length).toEqual(0)+ // Filters are reset with the initial `filterData`+ expect(uncheckedFilters.length).toEqual(22)})- it('clears filters', () => {- const wrapper = render(SearchGridFilter, options)- wrapper.vm.onClearFilters()- expect(commitMock).toHaveBeenCalledWith('CLEAR_FILTERS')- })+ it('toggles search visibility', async () => {+ render(SearchGridFilter, options)+ expect(screen.getByTestId('filters-list')).toBeVisible()+ expect(screen.getByTestId('filters-list')).toHaveClass(+ 'search-filters__visible'+ )- it('toggles search visibility', () => {- const wrapper = render(SearchGridFilter, options)- wrapper.vm.onToggleSearchGridFilter()- expect(commitMock).toHaveBeenCalledWith('SET_FILTER_IS_VISIBLE', {- isFilterVisible: !storeMock.state.isFilterVisible,- })+ await fireEvent.click(screen.getByText('filter-list.hide'))+ expect(screen.getByTestId('filters-list')).not.toHaveClass(+ 'search-filters__visible'+ )})})diff --git a/test/unit/specs/components/search-grid-form.spec.js b/test/unit/specs/components/search-grid-form.spec.jsindex 8930e1f95..0a9f60fea 100644--- a/test/unit/specs/components/search-grid-form.spec.js+++ b/test/unit/specs/components/search-grid-form.spec.js@@ -1,20 +1,33 @@-import Vuex from 'vuex'-import { createLocalVue } from '@vue/test-utils'import SearchGridForm from '~/components/SearchGridForm'import render from '../../test-utils/render'-describe('BrowsePage', () => {- it('should render correct contents', () => {- const localVue = createLocalVue()- localVue.use(Vuex)+import { createLocalVue } from '@vue/test-utils'+import Vuex from 'vuex'++const localVue = createLocalVue()+localVue.use(Vuex)+const storeMock = new Vuex.Store({+ modules: {+ filter: {+ namespaced: true,+ state: { isFilterVisible: true },+ },+ search: {+ namespaced: true,+ state: { query: { q: 'foo' } },+ },+ },+})+describe('SearchGridForm', () => {+ it('should render correct contents', () => {const wrapper = render(SearchGridForm, {localVue,mocks: {$route: {path: '/search',- $store: { state: { isFilterVisible: true } },},},+ store: storeMock,})expect(wrapper.find('form').vm).toBeDefined()diff --git a/test/unit/specs/components/search-grid-wrapper.spec.js b/test/unit/specs/components/search-grid-wrapper.spec.jsindex cd5bf29af..080be613f 100644--- a/test/unit/specs/components/search-grid-wrapper.spec.js+++ b/test/unit/specs/components/search-grid-wrapper.spec.js@@ -1,12 +1,37 @@import SearchGrid from '~/components/SearchGrid'import render from '../../test-utils/render'+import { createLocalVue } from '@vue/test-utils'+import Vuex from 'vuex'++const localVue = createLocalVue()+localVue.use(Vuex)+const storeMock = new Vuex.Store({+ modules: {+ filter: {+ namespaced: true,+ state: {+ filters: {+ licenseTypes: [+ { code: 'commercial', name: 'Commercial usage' },+ { code: 'modification', name: 'Allows modification' },+ ],+ },+ },+ },+ search: {+ namespaced: true,+ state: { query: { q: 'foo' } },+ },+ },+})const options = {stubs: {ScrollButton: true,SearchGridManualLoad: true,},- mocks: { $store: { state: { query: { q: 'foo' } } } },+ localVue,+ store: storeMock,}describe('Search Grid Wrapper', () => {diff --git a/test/unit/specs/components/search-grid.spec.js b/test/unit/specs/components/search-grid.spec.jsindex 21d529e6a..97cce1b5f 100644--- a/test/unit/specs/components/search-grid.spec.js+++ b/test/unit/specs/components/search-grid.spec.js@@ -1,39 +1,69 @@import SearchGrid from '~/components/SearchGridManualLoad'import render from '../../test-utils/render'+import { SET_MEDIA } from '~/constants/mutation-types'+import filterStore from '~/store/filter'+import searchStore from '~/store/search'++import Vuex from 'vuex'+import { IMAGE } from '~/constants/media'describe('SearchGrid', () => {let options = {}let commitMock = null+ let storeMock+ let searchStoreMockbeforeEach(() => {commitMock = jest.fn()+ searchStoreMock = {+ state: {+ images: [{ id: 'foo', title: 'image1.jpg' }],+ imagesCount: 1,+ imagePage: 1,+ isFetching: {+ images: false,+ },+ isFetchingError: {+ images: false,+ },+ pageCount: {+ images: 2,+ },+ searchType: IMAGE,+ },+ getters: searchStore.getters,+ actions: searchStore.actions,+ mutations: {+ ...searchStore.mutations,+ [SET_MEDIA]: commitMock,+ },+ }+ storeMock = new Vuex.Store({+ modules: {+ filter: {+ namespaced: true,+ ...filterStore,+ },+ search: {+ namespaced: true,+ ...searchStoreMock,+ },+ },+ })options = {+ store: storeMock,stubs: {- SearchRating: true,SaferBrowsing: true,LoadingIcon: true,MetaSearchForm: true,+ SearchGridCell: true,+ SearchRating: true,},propsData: {- query: { q: 'foo' },includeAnalytics: true,},mocks: {- $store: {- state: {- isFetching: {- images: false,- },- isFetchingError: {- images: false,- },- pageCount: {- images: 5,- },- imagesCount: 100,- imagePage: 1,- },- commit: commitMock,- },+ $store: storeMock,+ store: storeMock,},}})@@ -50,13 +80,13 @@ describe('SearchGrid', () => {})it("doesn't render load more button if is loading images", () => {- options.mocks.$store.state.isFetching.images = true+ options.mocks.$store.state.search.isFetching.images = trueconst wrapper = render(SearchGrid, options)expect(wrapper.find('.load-more').vm).not.toBeDefined()})it('shows loading icon if is loading images', () => {- options.mocks.$store.state.isFetching.images = true+ options.mocks.$store.state.search.isFetching.images = trueconst wrapper = render(SearchGrid, options)expect(wrapper.findComponent({ name: 'LoadingIcon' })).toBeDefined()@@ -75,14 +105,14 @@ describe('SearchGrid', () => {},])})-- it('sets image to empty array on search changed', () => {- const wrapper = render(SearchGrid, options)- wrapper.vm.searchChanged()-- expect(commitMock).toHaveBeenCalledWith('SET_MEDIA', {- media: [],- page: 1,- })- })+ // TODO: SearchGrid should be replaced with ImageGrid, and tested with testing library+ // it('sets image to empty array on search changed', () => {+ // const wrapper = render(SearchGrid, options)+ // wrapper.vm.searchChanged()+ //+ // expect(commitMock).toHaveBeenLastCalledWith(`${SEARCH}/${SET_MEDIA}`, {+ // media: [],+ // page: 1,+ // })+ // })})diff --git a/test/unit/specs/pages/browse-page.spec.js b/test/unit/specs/pages/browse-page.spec.jsindex c5caab767..46d9b8068 100644--- a/test/unit/specs/pages/browse-page.spec.js+++ b/test/unit/specs/pages/browse-page.spec.js@@ -1,28 +1,50 @@import BrowsePage from '~/pages/search'import render from '../../test-utils/render'--const options = {- stubs: {- AppModal: true,- FilterDisplay: true,- NuxtChild: true,- ScrollButton: true,- SearchGridFilter: true,- SearchGridForm: true,- SearchTypeTabs: true,- SearchGridManualLoad: true,- },- mocks: {- $store: {- commit: jest.fn(),- state: { query: { q: 'foo' }, isFilterVisible: false },- },- $router: { path: { name: 'search-image' } },- $route: { path: '/search/image' },- },-}+import { createLocalVue } from '@vue/test-utils'+import Vuex from 'vuex'describe('Search Grid Wrapper', () => {+ let options+ let localVue+ let storeMock+ beforeEach(() => {+ localVue = createLocalVue()+ localVue.use(Vuex)+ storeMock = new Vuex.Store({+ modules: {+ search: {+ namespaced: true,+ state: {+ query: { q: 'foo' },+ },+ },+ filter: {+ namespaced: true,+ state: {+ isFilterVisible: false,+ },+ },+ },+ })+ options = {+ localVue,+ store: storeMock,+ stubs: {+ AppModal: true,+ FilterDisplay: true,+ NuxtChild: true,+ ScrollButton: true,+ SearchGridFilter: true,+ SearchGridForm: true,+ SearchTypeTabs: true,+ SearchGridManualLoad: true,+ },+ mocks: {+ $router: { path: { name: 'search-image' } },+ $route: { path: '/search/image' },+ },+ }+ })it('renders correct content', () => {const wrapper = render(BrowsePage, options)expect(wrapper.find('[data-testid="scroll-button"]').element).toBeDefined()diff --git a/test/unit/specs/store/filter-store.spec.js b/test/unit/specs/store/filter-store.spec.jsindex 33bfcb35e..6ef6eb47f 100644--- a/test/unit/specs/store/filter-store.spec.js+++ b/test/unit/specs/store/filter-store.spec.js@@ -1,28 +1,34 @@-import store, { filterData } from '~/store-modules/filter-store'-import { TOGGLE_FILTER } from '~/constants/action-types'+import store, { filterData } from '~/store/filter'+import {+ SET_FILTERS_FROM_URL,+ TOGGLE_FILTER,+ UPDATE_QUERY,+} from '~/constants/action-types'import {SET_FILTER,SET_PROVIDERS_FILTERS,CLEAR_FILTERS,SET_FILTER_IS_VISIBLE,+ REPLACE_FILTERS,} from '~/constants/mutation-types'+import { SEARCH } from '~/constants/store-modules'describe('Filter Store', () => {describe('state', () => {it('state contains licenses', () => {- const defaultState = store.state+ const defaultState = store.state()expect(defaultState.filters.licenses).toEqual(filterData.licenses)})it('state contains license types', () => {- const defaultState = store.state+ const defaultState = store.state()expect(defaultState.filters.licenseTypes).toEqual(filterData.licenseTypes)})it('state contains image types', () => {- const defaultState = store.state+ const defaultState = store.state()expect(defaultState.filters.imageCategories).toEqual(filterData.imageCategories@@ -30,7 +36,7 @@ describe('Filter Store', () => {})it('state contains imageExtensions', () => {- const defaultState = store.state+ const defaultState = store.state()expect(defaultState.filters.imageExtensions).toEqual(filterData.imageExtensions@@ -38,13 +44,13 @@ describe('Filter Store', () => {})it('state contains empty providers list', () => {- const defaultState = store.state+ const defaultState = store.state()expect(defaultState.filters.imageProviders).toEqual([])})it('state contains search by author', () => {- const defaultState = store.state+ const defaultState = store.state()expect(defaultState.filters.searchBy.author).toEqual(filterData.searchBy.author@@ -52,25 +58,25 @@ describe('Filter Store', () => {})it('state contains mature', () => {- const defaultState = store.state+ const defaultState = store.state()expect(defaultState.filters.mature).toEqual(filterData.mature)})it('state has filter hidden', () => {- const defaultState = store.state+ const defaultState = store.state()expect(defaultState.isFilterVisible).toBeFalsy()})it('isFilterVisible should be false when innerWidth property is undefined', () => {window.innerWidth = undefined- const state = store.state+ const state = store.state()expect(state.isFilterVisible).toBeFalsy()})it('isFilterVisible should be false when window width is less then 800', () => {window.innerWidth = 500- const state = store.state+ const state = store.state()expect(state.isFilterVisible).toBeFalsy()})})@@ -82,9 +88,11 @@ describe('Filter Store', () => {beforeEach(() => {state = {- searchType: 'image',- query: { q: 'foo' },- ...store.state,+ search: {+ searchType: 'image',+ query: { q: 'foo' },+ },+ ...store.state(),}mutations = store.mutationsgetters = store.getters@@ -94,20 +102,12 @@ describe('Filter Store', () => {mutations[SET_FILTER](state, { filterType: 'licenses', codeIdx: 0 })expect(state.filters.licenses[0].checked).toBeTruthy()- expect(state.query).toEqual(- expect.objectContaining({ license: state.filters.licenses[0].code })- )})it('SET_FILTER updates license type state', () => {mutations[SET_FILTER](state, { filterType: 'licenseTypes', codeIdx: 0 })expect(state.filters.licenseTypes[0].checked).toBeTruthy()- expect(state.query).toEqual(- expect.objectContaining({- license_type: state.filters.licenseTypes[0].code,- })- )})it('SET_FILTER updates imageExtensions state', () => {@@ -117,11 +117,6 @@ describe('Filter Store', () => {})expect(state.filters.imageExtensions[0].checked).toBeTruthy()- expect(state.query).toEqual(- expect.objectContaining({- extension: state.filters.imageExtensions[0].code,- })- )})it('SET_FILTER updates image types state', () => {@@ -131,27 +126,18 @@ describe('Filter Store', () => {})expect(state.filters.imageCategories[0].checked).toBeTruthy()- expect(state.query).toEqual(- expect.objectContaining({- categories: state.filters.imageCategories[0].code,- })- )})it('SET_FILTER updates search by creator', () => {mutations[SET_FILTER](state, { filterType: 'searchBy', codeIdx: 0 })expect(state.filters.searchBy[0].checked).toBeTruthy()- expect(state.query).toEqual(- expect.objectContaining({ searchBy: 'creator' })- )})it('SET_FILTER updates mature', () => {mutations[SET_FILTER](state, { filterType: 'mature' })expect(state.filters.mature).toBeTruthy()- expect(state.query).toEqual(expect.objectContaining({ mature: true }))})it('SET_FILTER toggles mature', () => {@@ -165,20 +151,12 @@ describe('Filter Store', () => {mutations[SET_FILTER](state, { filterType: 'aspectRatios', codeIdx: 0 })expect(state.filters.aspectRatios[0].checked).toBeTruthy()- expect(state.query).toEqual(- expect.objectContaining({- aspect_ratio: state.filters.aspectRatios[0].code,- })- )})it('SET_FILTER updates size', () => {mutations[SET_FILTER](state, { filterType: 'sizes', codeIdx: 0 })expect(state.filters.sizes[0].checked).toBeTruthy()- expect(state.query).toEqual(- expect.objectContaining({ size: state.filters.sizes[0].code })- )})it('SET_FILTER updates isFilterApplied with provider', () => {@@ -221,27 +199,6 @@ describe('Filter Store', () => {])})- it('CLEAR_FILTERS resets filters to initial state', async () => {- mutations[CLEAR_FILTERS]({- query: { q: 'foo' },- ...store.state,- })- expect(state.filters).toEqual(filterData)- })-- it('CLEAR_FILTERS sets providers filters checked to false', async () => {- state.filters.imageProviders = [- { code: 'met', name: 'Metropolitan', checked: true },- { code: 'flickr', name: 'Flickr', checked: false },- ]-- mutations[CLEAR_FILTERS](state)- expect(state.filters.imageProviders).toEqual([- { code: 'met', name: 'Metropolitan', checked: false },- { code: 'flickr', name: 'Flickr', checked: false },- ])- })-it('SET_FILTER_IS_VISIBLE updates state', () => {const params = { isFilterVisible: 'bar' }mutations[SET_FILTER_IS_VISIBLE](state, params)@@ -257,15 +214,221 @@ describe('Filter Store', () => {let actions = nullbeforeEach(() => {- state = {- query: { q: 'foo' },- ...store.state,- }+ state = store.state()commitMock = jest.fn()dispatchMock = jest.fn()actions = store.actions})+ it('SET_FILTERS_FROM_URL', () => {+ const url =+ 'https://wp.org/openverse/search/image?q=cat&license=cc0,by&searchBy=creator&extension=jpg&mature=true&source=met'+ actions[SET_FILTERS_FROM_URL](+ {+ commit: commitMock,+ dispatch: dispatchMock,+ state,+ },+ { url }+ )+ expect(commitMock).toHaveBeenCalledWith(REPLACE_FILTERS, {+ newFilterData: {+ aspectRatios: [+ {+ checked: false,+ code: 'tall',+ name: 'filters.aspect-ratios.tall',+ },+ {+ checked: false,+ code: 'wide',+ name: 'filters.aspect-ratios.wide',+ },+ {+ checked: false,+ code: 'square',+ name: 'filters.aspect-ratios.square',+ },+ ],+ audioCategories: [+ {+ checked: false,+ code: 'music',+ name: 'filters.audio-categories.music',+ },+ {+ checked: false,+ code: 'soundEffects',+ name: 'filters.audio-categories.sound-effects',+ },+ {+ checked: false,+ code: 'podcast',+ name: 'filters.audio-categories.podcast',+ },+ ],+ audioExtensions: [+ {+ checked: false,+ code: 'mp3',+ name: 'filters.audio-extensions.mp3',+ },+ {+ checked: false,+ code: 'ogg',+ name: 'filters.audio-extensions.ogg',+ },+ {+ checked: false,+ code: 'flac',+ name: 'filters.audio-extensions.flac',+ },+ ],+ audioProviders: [],+ durations: [+ { checked: false, code: 'short', name: 'filters.durations.short' },+ {+ checked: false,+ code: 'medium',+ name: 'filters.durations.medium',+ },+ { checked: false, code: 'long', name: 'filters.durations.long' },+ ],+ imageCategories: [+ {+ checked: false,+ code: 'photograph',+ name: 'filters.image-categories.photograph',+ },+ {+ checked: false,+ code: 'illustration',+ name: 'filters.image-categories.illustration',+ },+ {+ checked: false,+ code: 'digitized_artwork',+ name: 'filters.image-categories.digitized-artwork',+ },+ ],+ imageExtensions: [+ {+ checked: true,+ code: 'jpg',+ name: 'filters.image-extensions.jpg',+ },+ {+ checked: false,+ code: 'png',+ name: 'filters.image-extensions.png',+ },+ {+ checked: false,+ code: 'gif',+ name: 'filters.image-extensions.gif',+ },+ {+ checked: false,+ code: 'svg',+ name: 'filters.image-extensions.svg',+ },+ ],+ imageProviders: [],+ licenseTypes: [+ {+ checked: false,+ code: 'commercial',+ name: 'filters.license-types.commercial',+ },+ {+ checked: false,+ code: 'modification',+ name: 'filters.license-types.modification',+ },+ ],+ licenses: [+ { checked: true, code: 'cc0', name: 'filters.licenses.cc0' },+ { checked: false, code: 'pdm', name: 'filters.licenses.pdm' },+ { checked: true, code: 'by', name: 'filters.licenses.by' },+ { checked: false, code: 'by-sa', name: 'filters.licenses.by-sa' },+ { checked: false, code: 'by-nc', name: 'filters.licenses.by-nc' },+ { checked: false, code: 'by-nd', name: 'filters.licenses.by-nd' },+ {+ checked: false,+ code: 'by-nc-sa',+ name: 'filters.licenses.by-nc-sa',+ },+ {+ checked: false,+ code: 'by-nc-nd',+ name: 'filters.licenses.by-nc-nd',+ },+ ],+ mature: true,+ searchBy: [+ {+ checked: true,+ code: 'creator',+ name: 'filters.searchBy.creator',+ },+ ],+ sizes: [+ { checked: false, code: 'small', name: 'filters.sizes.small' },+ { checked: false, code: 'medium', name: 'filters.sizes.medium' },+ { checked: false, code: 'large', name: 'filters.sizes.large' },+ ],+ },+ })+ })+ it('CLEAR_FILTERS resets filters to initial state', async () => {+ state.filters.licenses = [+ { code: 'by', checked: true },+ { code: 'by-nc', checked: true },+ { code: 'by-nd', checked: true },+ ]+ actions[CLEAR_FILTERS]({+ commit: commitMock,+ dispatch: dispatchMock,+ state,+ })+ expect(commitMock).toHaveBeenCalledWith(REPLACE_FILTERS, {+ newFilterData: filterData,+ })+ expect(dispatchMock).toHaveBeenCalledWith(+ `${SEARCH}/${UPDATE_QUERY}`,+ null,+ { root: true }+ )+ })++ it('CLEAR_FILTERS sets providers filters checked to false', async () => {+ state.filters.imageProviders = [+ { code: 'met', name: 'Metropolitan', checked: true },+ { code: 'flickr', name: 'Flickr', checked: false },+ ]++ actions[CLEAR_FILTERS]({+ commit: commitMock,+ dispatch: dispatchMock,+ state,+ })+ const expectedFilters = {+ ...state.filters,+ imageProviders: [+ { code: 'met', name: 'Metropolitan', checked: false },+ { code: 'flickr', name: 'Flickr', checked: false },+ ],+ }+ expect(commitMock).toHaveBeenCalledWith(REPLACE_FILTERS, {+ newFilterData: expectedFilters,+ })+ expect(dispatchMock).toHaveBeenCalledWith(+ `${SEARCH}/${UPDATE_QUERY}`,+ null,+ { root: true }+ )+ })+it('TOGGLE_FILTER commits SET_FILTER with filter index', () => {state.filters.providers = [{ code: 'met', name: 'Metropolitan', checked: true },@@ -284,5 +447,177 @@ describe('Filter Store', () => {...params,})})++ it('TOGGLE_FILTER updates license state', () => {+ actions[TOGGLE_FILTER](+ { commit: commitMock, dispatch: dispatchMock, state },+ { filterType: 'licenses', code: 'cc0' }+ )+ expect(commitMock).toHaveBeenCalledWith(SET_FILTER, {+ filterType: 'licenses',+ code: 'cc0',+ codeIdx: 0,+ })+ expect(dispatchMock).toHaveBeenCalledWith(+ `${SEARCH}/${UPDATE_QUERY}`,+ null,+ { root: true }+ )+ })++ it('TOGGLE_FILTER updates license type state', () => {+ actions[TOGGLE_FILTER](+ { commit: commitMock, dispatch: dispatchMock, state },+ { filterType: 'licenseTypes', code: 'modification' }+ )++ expect(commitMock).toHaveBeenCalledWith(SET_FILTER, {+ filterType: 'licenseTypes',+ code: 'modification',+ codeIdx: 1,+ })+ expect(dispatchMock).toHaveBeenCalledWith(+ `${SEARCH}/${UPDATE_QUERY}`,+ null,+ { root: true }+ )+ })++ it('TOGGLE_FILTER updates imageExtensions state', () => {+ actions[TOGGLE_FILTER](+ { commit: commitMock, dispatch: dispatchMock, state },+ {+ filterType: 'imageExtensions',+ code: 'svg',+ }+ )++ expect(commitMock).toHaveBeenCalledWith(SET_FILTER, {+ filterType: 'imageExtensions',+ code: 'svg',+ codeIdx: 3,+ })++ expect(dispatchMock).toHaveBeenCalledWith(+ `${SEARCH}/${UPDATE_QUERY}`,+ null,+ { root: true }+ )+ })++ it('TOGGLE_FILTER updates image types state', () => {+ actions[TOGGLE_FILTER](+ { commit: commitMock, dispatch: dispatchMock, state },+ {+ filterType: 'imageCategories',+ code: 'photograph',+ }+ )+ expect(commitMock).toHaveBeenCalledWith(SET_FILTER, {+ filterType: 'imageCategories',+ code: 'photograph',+ codeIdx: 0,+ })++ expect(dispatchMock).toHaveBeenCalledWith(+ `${SEARCH}/${UPDATE_QUERY}`,+ null,+ { root: true }+ )+ })++ it('TOGGLE_FILTER updates search by creator', () => {+ actions[TOGGLE_FILTER](+ { commit: commitMock, dispatch: dispatchMock, state },+ { filterType: 'searchBy', code: 'creator' }+ )++ expect(commitMock).toHaveBeenCalledWith(SET_FILTER, {+ filterType: 'searchBy',+ code: 'creator',+ codeIdx: 0,+ })++ expect(dispatchMock).toHaveBeenCalledWith(+ `${SEARCH}/${UPDATE_QUERY}`,+ null,+ { root: true }+ )+ })++ it('TOGGLE_FILTER updates mature', () => {+ actions[TOGGLE_FILTER](+ { commit: commitMock, dispatch: dispatchMock, state },+ { filterType: 'mature' }+ )++ expect(commitMock).toHaveBeenCalledWith(SET_FILTER, {+ filterType: 'mature',+ codeIdx: -1,+ })++ expect(dispatchMock).toHaveBeenCalledWith(+ `${SEARCH}/${UPDATE_QUERY}`,+ null,+ { root: true }+ )+ })++ it('TOGGLE_FILTER updates aspect ratio', () => {+ actions[TOGGLE_FILTER](+ { commit: commitMock, dispatch: dispatchMock, state },+ { filterType: 'aspectRatios', code: 'tall' }+ )++ expect(commitMock).toHaveBeenCalledWith(SET_FILTER, {+ filterType: 'aspectRatios',+ code: 'tall',+ codeIdx: 0,+ })++ expect(dispatchMock).toHaveBeenCalledWith(+ `${SEARCH}/${UPDATE_QUERY}`,+ null,+ { root: true }+ )+ })++ it('TOGGLE_FILTER updates size', () => {+ actions[TOGGLE_FILTER](+ { commit: commitMock, dispatch: dispatchMock, state },+ { filterType: 'sizes', code: 'medium' }+ )++ expect(commitMock).toHaveBeenCalledWith(SET_FILTER, {+ filterType: 'sizes',+ code: 'medium',+ codeIdx: 1,+ })++ expect(dispatchMock).toHaveBeenCalledWith(+ `${SEARCH}/${UPDATE_QUERY}`,+ null,+ { root: true }+ )+ })++ it('TOGGLE_FILTER toggles mature', () => {+ state.filters.mature = true+ actions[TOGGLE_FILTER](+ { commit: commitMock, dispatch: dispatchMock, state },+ { filterType: 'mature' }+ )++ expect(commitMock).toHaveBeenCalledWith(SET_FILTER, {+ filterType: 'mature',+ codeIdx: -1,+ })++ expect(dispatchMock).toHaveBeenCalledWith(+ `${SEARCH}/${UPDATE_QUERY}`,+ null,+ { root: true }+ )+ })})})diff --git a/test/unit/specs/store/search-store.spec.js b/test/unit/specs/store/search-store.spec.jsindex ae0959f24..6db5a7ee9 100644--- a/test/unit/specs/store/search-store.spec.js+++ b/test/unit/specs/store/search-store.spec.js@@ -1,4 +1,4 @@-import store from '~/store-modules/search-store'+import store, { createActions } from '~/store/search'import {FETCH_END_MEDIA,FETCH_MEDIA_ERROR,@@ -27,12 +27,12 @@ import {SEND_RESULT_CLICKED_EVENT,SEND_SEARCH_QUERY_EVENT,} from '~/constants/usage-data-analytics-types'-import { USAGE_DATA } from '~/constants/store-modules'+import { FILTER, USAGE_DATA } from '~/constants/store-modules'describe('Search Store', () => {describe('state', () => {it('exports default state', () => {- const state = store.state+ const state = store.state()expect(state.audios).toHaveLength(0)expect(state.audiosCount).toBe(0)expect(state.audioPage).toBe(1)@@ -55,11 +55,7 @@ describe('Search Store', () => {const mutations = store.mutationsbeforeEach(() => {- state = {- isFetching: {},- isFetchingError: {},- pageCount: {},- }+ state = store.state()})it('FETCH_START_MEDIA updates state', () => {@@ -208,11 +204,8 @@ describe('Search Store', () => {let services = nulllet audioServiceMock = nulllet imageServiceMock = null- let commit = null- let dispatch = null- let state = {}- let rootState = {}-+ let state+ let contextbeforeEach(() => {imageServiceMock = {search: jest.fn(() => Promise.resolve({ data: searchData })),@@ -233,24 +226,27 @@ describe('Search Store', () => {),}services = { [AUDIO]: audioServiceMock, [IMAGE]: imageServiceMock }- commit = jest.fn()- dispatch = jest.fn()state = {audios: [{ id: 'foo' }, { id: 'bar' }, { id: 'zeta' }],images: [{ id: 'foo' }, { id: 'bar' }, { id: 'zeta' }],query: { q: 'foo query' },}- rootState = { user: { usageSessionId: 'foo' } }- store.rootState = rootState++ context = {+ commit: jest.fn(),+ dispatch: jest.fn(),+ rootState: { user: { usageSessionId: 'foo' } },+ state: state,+ }})it('FETCH_MEDIA throws an error on unknown media type', async () => {- const action = store.actions(services)[FETCH_MEDIA]+ const action = createActions(services)[FETCH_MEDIA]const params = {mediaType: 'unknown',page: 1,}- await expect(action({ commit, dispatch, state }, params)).rejects.toThrow(+ await expect(action(context, params)).rejects.toThrow('Cannot fetch unknown media type "unknown"')})@@ -262,14 +258,16 @@ describe('Search Store', () => {shouldPersistMedia: false,mediaType: IMAGE,}- const action = store.actions(services)[FETCH_MEDIA]- await action({ commit, dispatch, state }, params)- expect(commit).toHaveBeenCalledWith(FETCH_START_MEDIA, {+ const action = createActions(services)[FETCH_MEDIA]+ await action(context, params)+ expect(context.commit).toHaveBeenCalledWith(FETCH_START_MEDIA, {+ mediaType: IMAGE,+ })+ expect(context.commit).toHaveBeenCalledWith(FETCH_END_MEDIA, {mediaType: IMAGE,})- expect(commit).toHaveBeenCalledWith(FETCH_END_MEDIA, { mediaType: IMAGE })- expect(commit).toHaveBeenCalledWith(SET_MEDIA, {+ expect(context.commit).toHaveBeenCalledWith(SET_MEDIA, {media: searchData.results,mediaCount: searchData.result_count,shouldPersistMedia: params.shouldPersistMedia,@@ -281,15 +279,16 @@ describe('Search Store', () => {it('FETCH_MEDIA dispatches SEND_SEARCH_QUERY_EVENT', async () => {const params = { q: 'foo', shouldPersistMedia: false, mediaType: IMAGE }- const action = store.actions(services)[FETCH_MEDIA]- await action({ commit, dispatch, state, rootState }, params)+ const action = createActions(services)[FETCH_MEDIA]+ await action(context, params)- expect(dispatch).toHaveBeenCalledWith(+ expect(context.dispatch).toHaveBeenCalledWith(`${USAGE_DATA}/${SEND_SEARCH_QUERY_EVENT}`,{query: params.q,- sessionId: rootState.user.usageSessionId,- }+ sessionId: context.rootState.user.usageSessionId,+ },+ { root: true })})@@ -300,13 +299,16 @@ describe('Search Store', () => {shouldPersistMedia: false,mediaType: IMAGE,}- const action = store.actions(services)[FETCH_MEDIA]- await action({ commit, dispatch, state }, params)+ const action = createActions(services)[FETCH_MEDIA]+ await action(context, params)- expect(dispatch).not.toHaveBeenCalledWith('SEND_SEARCH_QUERY_EVENT', {- query: params.q,- sessionId: state.usageSessionId,- })+ expect(context.dispatch).not.toHaveBeenCalledWith(+ `${USAGE_DATA}/${SEND_SEARCH_QUERY_EVENT}`,+ {+ query: params.q,+ sessionId: context.rootState.user.usageSessionId,+ }+ )})it('FETCH_MEDIA on error', async () => {@@ -320,12 +322,14 @@ describe('Search Store', () => {shouldPersistMedia: false,mediaType,}- const action = store.actions(services)[FETCH_MEDIA]- await action({ commit, dispatch, state }, params)+ const action = createActions(services)[FETCH_MEDIA]+ await action(context, params)await expect(services[IMAGE].search).rejects.toEqual('error')- expect(commit).toHaveBeenCalledWith(FETCH_START_MEDIA, { mediaType })- expect(dispatch).toHaveBeenCalledWith('HANDLE_MEDIA_ERROR', {+ expect(context.commit).toHaveBeenCalledWith(FETCH_START_MEDIA, {+ mediaType,+ })+ expect(context.dispatch).toHaveBeenCalledWith(HANDLE_MEDIA_ERROR, {error: 'error',mediaType,})@@ -339,12 +343,16 @@ describe('Search Store', () => {shouldPersistMedia: false,mediaType,}- const action = store.actions(services)[FETCH_MEDIA]- await action({ commit, dispatch, state, rootState }, params)+ const action = createActions(services)[FETCH_MEDIA]+ await action(context, params)- expect(commit).toHaveBeenCalledWith(FETCH_START_MEDIA, { mediaType })- expect(commit).toHaveBeenCalledWith(RESET_MEDIA, { mediaType })- expect(commit).toHaveBeenCalledWith(FETCH_END_MEDIA, { mediaType })+ expect(context.commit).toHaveBeenCalledWith(FETCH_START_MEDIA, {+ mediaType,+ })+ expect(context.commit).toHaveBeenCalledWith(RESET_MEDIA, { mediaType })+ expect(context.commit).toHaveBeenCalledWith(FETCH_END_MEDIA, {+ mediaType,+ })})it('FETCH_MEDIA does not reset images if page is defined', async () => {@@ -355,34 +363,39 @@ describe('Search Store', () => {shouldPersistMedia: false,mediaType,}- const action = store.actions(services)[FETCH_MEDIA]- await action({ commit, dispatch, state }, params)+ const action = createActions(services)[FETCH_MEDIA]+ await action(context, params)- expect(commit).not.toHaveBeenCalledWith(RESET_MEDIA, { mediaType })+ expect(context.commit).not.toHaveBeenCalledWith(RESET_MEDIA, {+ mediaType,+ })})it('FETCH_AUDIO on success', async () => {const params = { id: 'foo' }- const action = store.actions(services)[FETCH_AUDIO]- await action({ commit, dispatch, state, rootState }, params)- expect(commit).toHaveBeenCalledWith(SET_AUDIO, { audio: {} })- expect(commit).toHaveBeenCalledWith(SET_AUDIO, { audio: audioDetailData })+ const action = createActions(services)[FETCH_AUDIO]+ await action(context, params)+ expect(context.commit).toHaveBeenCalledWith(SET_AUDIO, { audio: {} })+ expect(context.commit).toHaveBeenCalledWith(SET_AUDIO, {+ audio: audioDetailData,+ })expect(audioServiceMock.getMediaDetail).toHaveBeenCalledWith(params)})it('FETCH_AUDIO dispatches SEND_RESULT_CLICKED_EVENT', () => {const params = { id: 'foo' }- const action = store.actions(services)[FETCH_AUDIO]- action({ commit, dispatch, state, rootState }, params)+ const action = createActions(services)[FETCH_AUDIO]+ action(context, params)- expect(dispatch).toHaveBeenLastCalledWith(+ expect(context.dispatch).toHaveBeenLastCalledWith(`${USAGE_DATA}/${SEND_RESULT_CLICKED_EVENT}`,{query: state.query.q,resultUuid: 'foo',resultRank: 0,- sessionId: rootState.user.usageSessionId,- }+ sessionId: context.rootState.user.usageSessionId,+ },+ { root: true })})@@ -391,11 +404,11 @@ describe('Search Store', () => {getMediaDetail: jest.fn(() => Promise.reject('error')),}const params = { id: 'foo' }- const action = store.actions(services)[FETCH_AUDIO]- await action({ commit, dispatch, state, rootState }, params)+ const action = createActions(services)[FETCH_AUDIO]+ await action(context, params)await expect(services[AUDIO].getMediaDetail).rejects.toEqual('error')- expect(dispatch).toHaveBeenLastCalledWith('HANDLE_MEDIA_ERROR', {+ expect(context.dispatch).toHaveBeenLastCalledWith(HANDLE_MEDIA_ERROR, {error: 'error',mediaType: 'audio',})@@ -409,34 +422,39 @@ describe('Search Store', () => {),}const params = { id: 'foo' }- const action = store.actions(services)[FETCH_AUDIO]- await action({ commit, dispatch, state, rootState }, params)- expect(commit).toHaveBeenCalledWith(MEDIA_NOT_FOUND, { mediaType })+ const action = createActions(services)[FETCH_AUDIO]+ await action(context, params)+ expect(context.commit).toHaveBeenCalledWith(MEDIA_NOT_FOUND, {+ mediaType,+ })})it('FETCH_IMAGE on success', async () => {const params = { id: 'foo' }- const action = store.actions(services)[FETCH_IMAGE]- await action({ commit, dispatch, state, rootState }, params)- expect(commit).toHaveBeenCalledWith(SET_IMAGE, { image: {} })- expect(commit).toHaveBeenCalledWith(SET_IMAGE, { image: imageDetailData })+ const action = createActions(services)[FETCH_IMAGE]+ await action(context, params)+ expect(context.commit).toHaveBeenCalledWith(SET_IMAGE, { image: {} })+ expect(context.commit).toHaveBeenCalledWith(SET_IMAGE, {+ image: imageDetailData,+ })expect(imageServiceMock.getMediaDetail).toHaveBeenCalledWith(params)})it('FETCH_IMAGE dispatches SEND_RESULT_CLICKED_EVENT', () => {const params = { id: 'foo' }- const action = store.actions(services)[FETCH_IMAGE]- action({ commit, dispatch, state, rootState }, params)+ const action = createActions(services)[FETCH_IMAGE]+ action(context, params)- expect(dispatch).toHaveBeenLastCalledWith(+ expect(context.dispatch).toHaveBeenLastCalledWith(`${USAGE_DATA}/${SEND_RESULT_CLICKED_EVENT}`,{query: state.query.q,resultUuid: 'foo',resultRank: 0,- sessionId: rootState.user.usageSessionId,- }+ sessionId: context.rootState.user.usageSessionId,+ },+ { root: true })})@@ -447,10 +465,10 @@ describe('Search Store', () => {),}const params = { id: 'foo' }- const action = store.actions(services)[FETCH_IMAGE]- await expect(- action({ commit, dispatch, state, rootState }, params)- ).rejects.toThrow('Error fetching the image: Server error')+ const action = createActions(services)[FETCH_IMAGE]+ await expect(action(context, params)).rejects.toThrow(+ 'Error fetching the image: Server error'+ )})it('FETCH_IMAGE on 404 doesnt break and commits MEDIA_NOT_FOUND', async () => {@@ -461,81 +479,95 @@ describe('Search Store', () => {),}const params = { id: 'foo' }- const action = store.actions(services)[FETCH_IMAGE]- await action({ commit, dispatch, state, rootState }, params)- expect(commit).toHaveBeenCalledWith(MEDIA_NOT_FOUND, { mediaType })+ const action = createActions(services)[FETCH_IMAGE]+ await action(context, params)+ expect(context.commit).toHaveBeenCalledWith(MEDIA_NOT_FOUND, {+ mediaType,+ })})it('HANDLE_MEDIA_ERROR handles 500 error', () => {- const action = store.actions(services)[HANDLE_MEDIA_ERROR]+ const action = createActions(services)[HANDLE_MEDIA_ERROR]const error = { response: { status: 500, message: 'Server error' } }- action({ commit }, { mediaType: AUDIO, error })- expect(commit).toHaveBeenCalledWith(FETCH_MEDIA_ERROR, {+ action(context, { mediaType: AUDIO, error })+ expect(context.commit).toHaveBeenCalledWith(FETCH_MEDIA_ERROR, {errorMessage: 'There was a problem with our servers',mediaType: AUDIO,})})it('HANDLE_MEDIA_ERROR handles a 403 error', () => {- const action = store.actions(services)[HANDLE_MEDIA_ERROR]+ const action = createActions(services)[HANDLE_MEDIA_ERROR]const error = { response: { status: 403, message: 'Server error' } }- action({ commit }, { mediaType: AUDIO, error })- expect(commit).toHaveBeenCalledWith(FETCH_MEDIA_ERROR, {+ action(context, { mediaType: AUDIO, error })+ expect(context.commit).toHaveBeenCalledWith(FETCH_MEDIA_ERROR, {errorMessage: error.response.message,mediaType: AUDIO,})})it('HANDLE_MEDIA_ERROR throws a new error on error when server did not respond', async () => {- const action = store.actions(services)[HANDLE_MEDIA_ERROR]+ const action = createActions(services)[HANDLE_MEDIA_ERROR]const error = new Error('Server did not respond')await expect(- action({ commit }, { mediaType: AUDIO, error })+ action(context, { mediaType: AUDIO, error })).rejects.toThrow(error.message)})it('HANDLE_NO_MEDIA throws an error when media count is 0', async () => {- const action = store.actions(services)[HANDLE_NO_MEDIA]- await action({ commit }, { mediaCount: 0, mediaType: IMAGE })- expect(commit).toHaveBeenLastCalledWith(FETCH_MEDIA_ERROR, {+ const action = createActions(services)[HANDLE_NO_MEDIA]+ await action(context, { mediaCount: 0, mediaType: IMAGE })+ expect(context.commit).toHaveBeenLastCalledWith(FETCH_MEDIA_ERROR, {errorMessage: 'No image found for this query',})})it('HANDLE_NO_MEDIA does not throw an error when media count is not 0', () => {- const action = store.actions(services)[HANDLE_NO_MEDIA]- action({ commit }, { mediaCount: 1, mediaType: IMAGE })- expect(commit.mock.calls.length).toEqual(0)+ const action = createActions(services)[HANDLE_NO_MEDIA]+ action(context, { mediaCount: 1, mediaType: IMAGE })+ expect(context.commit.mock.calls.length).toEqual(0)})it('SET_SEARCH_TYPE_FROM_URL sets search type to image', () => {- const action = store.actions(services)[SET_SEARCH_TYPE_FROM_URL]- action({ commit }, { url: '/search/image?q=cat&source=met' })- expect(commit).toHaveBeenCalledWith(SET_SEARCH_TYPE, {+ const action = createActions(services)[SET_SEARCH_TYPE_FROM_URL]+ action(context, { url: '/search/image?q=cat&source=met' })+ expect(context.commit).toHaveBeenCalledWith(SET_SEARCH_TYPE, {searchType: IMAGE,})- expect(commit).toHaveBeenCalledWith(UPDATE_FILTERS)+ expect(context.commit).toHaveBeenCalledWith(+ `${FILTER}/${UPDATE_FILTERS}`,+ { searchType: IMAGE },+ { root: true }+ )})it('SET_SEARCH_TYPE_FROM_URL sets search type to ALL_MEDIA if URL param is not set', () => {- const action = store.actions(services)[SET_SEARCH_TYPE_FROM_URL]- action({ commit }, { url: '/search/?q=cat&source=met' })- expect(commit).toHaveBeenCalledWith(SET_SEARCH_TYPE, {+ const action = createActions(services)[SET_SEARCH_TYPE_FROM_URL]+ action(context, { url: '/search/?q=cat&source=met' })+ expect(context.commit).toHaveBeenCalledWith(SET_SEARCH_TYPE, {searchType: ALL_MEDIA,})- expect(commit).toHaveBeenCalledWith(UPDATE_FILTERS)+ expect(context.commit).toHaveBeenCalledWith(+ `${FILTER}/${UPDATE_FILTERS}`,+ { searchType: 'all' },+ { root: true }+ )})it('UPDATE_SEARCH_TYPE sets search type to ALL_MEDIA if URL param is not set', () => {- const action = store.actions(services)[UPDATE_SEARCH_TYPE]+ const action = createActions(services)[UPDATE_SEARCH_TYPE]- action({ commit }, { searchType: ALL_MEDIA })- expect(commit).toHaveBeenCalledWith(SET_SEARCH_TYPE, {+ action(context, { searchType: ALL_MEDIA })+ expect(context.commit).toHaveBeenCalledWith(SET_SEARCH_TYPE, {searchType: ALL_MEDIA,})- expect(commit).toHaveBeenCalledWith(UPDATE_FILTERS)+ expect(context.commit).toHaveBeenCalledWith(+ `${FILTER}/${UPDATE_FILTERS}`,+ { searchType: 'all' },+ { root: true }+ )})})})diff --git a/test/unit/specs/utils/search-query-transform.spec.js b/test/unit/specs/utils/search-query-transform.spec.jsindex 808a916df..ab4a8a668 100644--- a/test/unit/specs/utils/search-query-transform.spec.js+++ b/test/unit/specs/utils/search-query-transform.spec.js@@ -4,7 +4,7 @@ import {queryToFilterData,queryStringToQueryData,} from '~/utils/search-query-transform'-import { filterData } from '~/store-modules/filter-store'+import { filterData } from '~/store/filter'import { IMAGE } from '~/constants/media'describe('searchQueryTransform', () => {diff --git a/test/unit/test-utils/sample-store.js b/test/unit/test-utils/sample-store.jsindex 4f48eb05c..004432600 100644--- a/test/unit/test-utils/sample-store.js+++ b/test/unit/test-utils/sample-store.js@@ -1,4 +1,4 @@-import SearchStore from '~/store-modules/search-store'+import SearchStore from '~/store/search'import MediaProviderStore from '~/store/provider'const store = {