How can I test onload javascript event in Vue/NUXT mounted hook?

Viewed 16

I've got a terrible code which I need to add test on.

  mounted() {
    const script = document.createElement("script");
    script.setAttribute("src", "https://jestjs.io");
    script.onload = () => {
      this.init(); <---------------Testing this function 
    };
    document.body.appendChild(script);
  },

I am testing the init function which needs to be called after component has been mounted. But it will never be called because the script.onload doesn't exist for some reason

This is my test and it is failing:

  it.only("should call call init method on load", () => {
    const mockMethod = jest.spyOn(Component.options.methods, "init");

    const wrapper = shallowMount(Component, {
      mocks: {
        $i18n: {
          locale: "en",
        },
        $config: { public: config },
      },
    });

    // wrapper.vm.init(); <-------------if I invoke the method manually then tests are passing

    expect(mockMethod).toHaveBeenCalled();
  });
0 Answers
Related