user762579
user762579

Reputation:

vue.js est unit -How to test a a watcher based on computed value ? ( setComputed is deprecated)

I have a watcher on language in my component I get the current language from a getter ( its value is changed from the Toolbar language selector, default in state.language is "en")

ContactForm.vue

  ...
  data() {
    return {
      contactLang: "",
      ...
    };
  },
  computed: {
        ...mapGetters(["language"]),
      },
      watch: {
        language(newLanguage) {
          console.lo("language changed to: ", newLanguage);
          this.contactLang = newLanguage;
          this.$validator.localize(newLanguage);
        }
      },

======================

I am trying to test the watch block

ContactForm.spec.js

beforeEach(() => {
    // create a fresh store instance for every test case.
    storeMocks = createStoreMocks();
    options = {
      sync: false,
      provide: () => ({
        $validator: v
      }),
      store: storeMocks.store,
      i18n
    };
    wrapper = shallowMount(ContactForm, options);
  });


  it("change the form language when locale changed", () => {
    // update the Vuex store language , but it does not trigger the watcher ...
    wrapper.vm.$store.state.language = "fr";
    expect(wrapper.vm.contactLang).toBe("fr");
  });

Is there any way to test this watch block , or should I restructure my code to avoid such testing in this component...

Upvotes: 1

Views: 520

Answers (1)

user762579
user762579

Reputation:

I solved the issue... watchers are asynchronous so I just delay the assertion

  it("change the form language when locale changed", () => {
    // pdate the Vuex store language , but it does not trigger the watcher ...
    wrapper.vm.$store.state.language = "fr";
    setTimeout(() => {
      // assert changes operated by watcher
      expect(wrapper.vm.contactLang).toBe("fr");
  }, 50);
  });

Upvotes: 1

Related Questions