Stavros Anastasiadis
Stavros Anastasiadis

Reputation: 413

NuxtJS , Unit Test language picker with Jest and nuxt-i18n

I have a component that switch Language of a nuxtjs application using nuxt-i18n as follows

<template>
  <div class="navbar-item has-dropdown is-hoverable">
    <a class="navbar-link langpicker">{{ $t("language_picker") }} </a>
    <div class="navbar-dropdown is-hidden-mobile">
      <div>
        <nuxt-link
          v-if="currentLanguage != 'en'"
          class="navbar-item"
          :to="switchLocalePath('en')"
        >
          <img src="~/static/flags/us.svg" class="flagIcon" /> English
        </nuxt-link>
        <nuxt-link
          v-if="currentLanguage != 'el'"
          class="navbar-item"
          :to="switchLocalePath('el')"
        >
          <img src="~/static/flags/el.svg" class="flagIcon" /> Ελληνικά
        </nuxt-link>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "LangPicker",
  computed: {
    currentLanguage() {
      return this.$i18n.locale || "en";
    }
  }
};
</script>

I want to write a Unit Test that test the correct language switch on 'nuxt-link' click.

So far I have the following

import { mount, RouterLinkStub } from "@vue/test-utils";
import LangPicker from "@/components/layout/LangPicker";

describe("LangPicker with locale en", () => {
  let cmp;
  beforeEach(() => {
    cmp = mount(LangPicker, {
      mocks: {
        $t: msg => msg,
        $i18n: { locale: "en" },
        switchLocalePath: msg => msg
      },
      stubs: {
        NuxtLink: RouterLinkStub
      }
    });
  });

  it("Trigger language", () => {
    const el = cmp.findAll(".navbar-item")
  });
});

cmp.find(".navbar-item") return an empty object.

I don't know how I must set up to "trigger" the click event.

const el = cmp.findAll(".navbar-item")[1].trigger("click");

Upvotes: 2

Views: 1059

Answers (1)

Sanath
Sanath

Reputation: 4886

make sure your find selector is correct.

const comp = cmp.find(".navbar-item");
comp.trigger('click');

you can use chrome dev tools selector utility. Refer this link for detailed information.

Upvotes: 1

Related Questions