66

As typeof returns "object"..

var MyBlob = new Blob(['test text'], {type : 'text/plain'});
console.log(typeof MyBlob) // "object"

is it too early to ask for a generic solution for checking whether or not a variable is a blob as it is not yet widely supported? Or how should I go about testing for blob type in browsers which already have it implemented?

Jaak Kütt
  • 2,566
  • 4
  • 31
  • 39

2 Answers2

120

You can test if it is an instanceof Blob like this:

var MyBlob = new Blob(['test text'], {type : 'text/plain'});
document.body.innerHTML = MyBlob instanceof Blob;

This will work for things that inherit from Blob also.

EzioMercer
  • 1,502
  • 2
  • 7
  • 23
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • As @jfriend00 said, this works for things that inherit from Blob as well. Since File inherits from Blob, the above evaluates also to true if MyBlob is actually an instance of File. – Marnix.hoh Apr 29 '20 at 13:57
6

Note that instanceof needs to be passed the exact constructor function used to create the object!

This isn't always the case in NodeJS, since it doesn't have a global Blob implementation (so we're dealing with polyfills).

For example, node-fetch uses an internal Blob implementation, but if you're using jest in a test suite (which polyfills Blob), you'll notice that expect(myBlob).toBeInstanceOf(Blob); will throw an exception similar to:

expect(value).toBeInstanceOf(constructor)

Expected constructor: Blob
Received constructor: Blob

In such cases, the best we can do is:

const fetch = require('node-fetch');
fetch(/* some request */).then(res => {
  const myBlob = await res.blob(); // a Blob created by node-fetch
  console.log(myBlob.constructor.name === 'Blob'); // true
});
Matthemattics
  • 9,577
  • 1
  • 21
  • 18