vue.js单元:测试w test-utils和Jest:如何测试方法中的window.open()?

时间:2018-09-05 15:38:42

标签: unit-testing vue.js jestjs vue-test-utils

在我的AudioPlayer组件中,我有一个download()方法:

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

我可以测试第一行:

this.audio.pause();

但是我该如何测试(我应该吗?第二行:

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

这是我当前的规格文件测试

  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);
  });

感谢您的反馈

2 个答案:

答案 0 :(得分:1)

您可以用开玩笑的模拟功能替换window.open,然后照常测试模拟调用。

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

答案 1 :(得分:0)

您可以检查window.open是否被呼叫

const spy = jest.spyOn(window, 'open');
expect(spy).toHaveBeenCalledTimes(1)