score:62

Accepted answer

this would appear to be as simple as setting up url on the global in jest. something like

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

this should result in a test that you can also use for checking if global.url.createobjecturl was called. as a side note: you may also run into a similar issue with window.open i would suggest mocking that as well if this becomes the case.

score:-1

use webkiturl.createobjecturl instead of url.createobjecturl its work for me

score:0

the package jsdom-worker happens to provide this method, as well as adding support for web workers. the following worked for me:

npm install -d jsdom-worker

then in package.json, edit or add a jest key:

{
  ...
  "jest": {
    "setupfiles": [
      "jsdom-worker"
    ]
  }
}

score:3

just mocking the function global.url.createobjecturl did not work for me, because the function was used by some modules during import and i got the error jest url.createobjecturl is not a function during import.

instead it did help to create a file mockjsdom.js

object.defineproperty(url, 'createobjecturl', {
  writable: true,
  value: jest.fn()
})

then import this file as the first import in your file containing the test

import './mockjsdom'
import { myobjects} from '../../src/lib/mylib'

test('my test', () => {
  // test code
}

found here: https://jestjs.io/docs/manual-mocks#mocking-methods-which-are-not-implemented-in-jsdom

score:10

you just have to write this in your setuptest.js

window.url.createobjecturl = function() {};

score:18

jsdom, the javascript implementation of the whatwg dom used by jest doesn't implement this method yet.

you can find an open ticket about this exact issue on their github page where some workarounds are provided in comments. but if you need the bloburl to actually work you'll have to wait this fr is solved.

workaround proposed in the comments of the issue for jest:

function noop () { }
if (typeof window.url.createobjecturl === 'undefined') { 
  object.defineproperty(window.url, 'createobjecturl', { value: noop})
}

score:19

since window.url.createobjecturl is not (yet) available in jest-dom, you need to provide a mock implementation for it.

don't forget to reset the mock implementation after each test.

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

  aftereach(() => {
    window.url.createobjecturl.mockreset();
  });

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

Related Query

More Query from same tag