Search code examples
unit-testingvue.jsjestjsvue-test-utils

vue.js unit:test w test-utils and Jest : How can I test - window.open() in a method?


In my component AudioPlayer I have a download() method :

download() {
  this.audio.pause();
  window.open(this.file, "download");
},

I can test the first line :

this.audio.pause();

But how can I test ( should I ? the second line :

window.open(this.file, "download");

Here is my current spec file test

  it("should open a window from downloadBtn", async () => {
    // jsdom doesn't support any loading or playback media operations. 
    // As a workaround you can add a few stubs in your test setup:
    window.HTMLMediaElement.prototype.pause = () => { /* do nothing */ };
    // given
    const wrapper = mount(AudioPlayer, {
      attachToDocument: true,
      propsData: {
        autoPlay: false,
        file: file,
        ended,
        canPlay
      }
    });
    const downloadBtn = wrapper.find("#downloadBtn");
    wrapper.vm.loaded = true; // enable downloadBtn
    // when
    downloadBtn.trigger("click");
    await wrapper.vm.$nextTick();
    // then
    expect(wrapper.vm.paused).toBe(true);
  });

thanks for feedback


Solution

  • You may replace window.open with a jest mock function and then test mock calls as usual.

    window.open = jest.fn();
    window.open('foo');
    expect(window.open).toHaveBeenCalledWith('foo');