Jest URL.createObjectURL 不是函数

IT技术 javascript reactjs testing blob jestjs
2021-05-22 08:29:16

我正在开发一个 reactJs 应用程序。我正在使用 jest 来测试我的应用程序。我想测试一个下载 blob 的函数。

但不幸的是我收到了这个错误:

URL.createObjectURL 不是函数

我的测试功能:

describe('download', () => {
    const documentIntial = { content: 'aaa' };
    it('msSaveOrOpenBlob should not have been called when navigao is undefined', () => {
      window.navigator.msSaveOrOpenBlob = null;
      download(documentIntial);
      expect(window.navigator.msSaveOrOpenBlob).toHaveBeenCalledTimes(0);
    });
  });

我要测试的功能:

export const download = document => {
  const blob = new Blob([base64ToArrayBuffer(document.content)], {
    type: 'application/pdf',
  });
  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob);
    return;
  }

  const fileURL = URL.createObjectURL(blob);
  window.open(fileURL);
};
4个回答

这看起来就像URL在 Jest 中设置Global一样简单就像是

describe('download', () => {
  const documentIntial = { content: 'aaa' };
  global.URL.createObjectURL = jest.fn();
  it('msSaveOrOpenBlob should not have been called when navigao is undefined', () => {
    global.URL.createObjectURL = jest.fn(() => 'details');
window.navigator.msSaveOrOpenBlob = jest.fn(() => 'details');
download(documentIntial);
expect(window.navigator.msSaveOrOpenBlob).toHaveBeenCalledTimes(1);
  });
});

这应该会产生一个测试,你也可以用它来检查是否global.URL.createObjectURL被调用。附带说明:您也可能会遇到类似的问题,window.open如果情况如此我建议您也嘲笑一下。

在 jsdom 中,jest 使用的 WHATWG DOM 的 JavaScript 实现尚未实现此方法。

您可以在他们的github 页面找到有关此确切问题公开票证,其中评论中提供了一些解决方法。但是,如果您需要 blobURL 实际工作,则必须等待此 FR 解决。

开玩笑的问题评论中提出的解决方法:

function noOp () { }
if (typeof window.URL.createObjectURL === 'undefined') { 
  Object.defineProperty(window.URL, 'createObjectURL', { value: noOp})
}

由于window.URL.createObjectURL(尚未)在 jest-dom 中可用,您需要为它提供一个模拟实现。

不要忘记在每次测试后重置模拟实现。

describe("your test suite", () => {
  window.URL.createObjectURL = jest.fn();

  afterEach(() => {
    window.URL.createObjectURL.mockReset();
  });

  it("your test case", () => {
    expect(true).toBeTruthy();
  });
});

你只需要在你的 setupTest.js 中写这个

window.URL.createObjectURL = function() {};