algolia / vue-instantsearch

👀 Algolia components for building search UIs with Vue.js
https://www.algolia.com/doc/guides/building-search-ui/what-is-instantsearch/vue
MIT License
854 stars 157 forks source link

Algolia component testing - VueInstantSearch #1162

Closed BernardoSemiOficial closed 1 year ago

BernardoSemiOficial commented 1 year ago

hello, I'm working with the search algorithm with widgets for Vue. https://www.algolia.com/doc/guides/building-search-ui/getting-started/vue/

I'm having difficulty performing tests on these components, because when assembling them in the tests, they look like this '<!---->' and that way I can't make assertions.

Stats.vue needs a parent component called to be around for the child components to work. Because it is in it that access keys are passed to be able to fetch the data. So in the tests I needed to mount the parent around.

Stats.vue

<template>
  <ais-stats>
    <template v-slot="{ nbHits, query }">
      <p data-testid="stats-query" v-if="query">{{ query }}</p>
      <p v-if="nbHits" data-testid="stats-number-hits">
        {{ nbHits }} {{ nbHits > 1 ? 'itens' : 'item' }} em exibição
      </p>
    </template>
  </ais-stats>
</template>

<script lang="ts">
import { defineComponent } from '@marketplace/shared/utils'
export default defineComponent({
  name: 'Stats',
})
</script>
const searchClient = algoliasearch(
  'B1G2GM9NG0',
  'aadef574be1f9252bb48d4ea09b5cfe5'
)

const ParentAisInstantSearch = {
  template: `
    <ais-instant-search :index-name="indexName" :search-client="searchClient">
    </ais-instant-search>`,
  components: {
    AisInstantSearch,
  },
  data() {
    return {
      searchClient,
      indexName: 'demo_ecommerce',
    }
  },
}

describe('Stats.vue', () => {
  let wrapper: Wrapper<Vue & Stats>

  beforeEach(() => {
    wrapper = shallowMount(Stats, {
      localVue,
      parentComponent: ParentAisInstantSearch,
    })
  })

  it('Should render component', () => {
    // wrapper.html()
    `
    <ais-stats-stub>
      <!---->
      <!---->
    </ais-stats-stub>
    `
  })
})
Haroenv commented 1 year ago

The wrapper is correct, although the search client shouldn't be a real one, as you don't want to do a search in your unit tests. You can use a fake search client like available here (copy and paste in your project): https://github.com/algolia/instantsearch.js/blob/d7b62eda77d894a3677a0967a05a2a357e7e5a94/test/mock/createSearchClient.ts

In other cases you could write tests as we done in the Vue InstantSearch repo and mock the widget mixin, although it's somewhat less accurate (it requires you to know exactly what's returned in state