Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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


1 Answers

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');
like image 123
Oleksandr Kovpashko Avatar answered Oct 17 '25 08:10

Oleksandr Kovpashko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!