【问题标题】:vue.js unit:test w test-utils and Jest : How can I test - window.open() in a method?vue.js unit:test w test-utils 和 Jest:我如何在方法中测试 - window.open()?
【发布时间】:2019-02-10 19:47:43
【问题描述】:

在我的组件 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);
  });

感谢反馈

【问题讨论】:

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


    【解决方案1】:

    您可以将window.open 替换为一个开玩笑的模拟函数,然后像往常一样测试模拟调用。

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

    【讨论】:

    • 好! akl 已检查!
    【解决方案2】:

    你可以检查window.open是否被调用

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

    【讨论】:

      猜你喜欢
      • 2019-02-10
      • 2019-02-01
      • 2019-01-27
      • 1970-01-01
      • 2019-05-28
      • 2019-01-25
      • 2020-08-06
      • 2022-08-18
      • 2018-08-06
      相关资源
      最近更新 更多