Mike
Mike

Reputation: 31

Jest, Puppeteer, Typescript, ReferenceError: Blob is not defined

I'm developing a Typescript library and am trying to write tests with Jest and Puppeteer. The tests are failing because ReferenceError: Blob is not defined. I followed the Getting Started sections for both Jest and Jest-Puppeteer, but am still running into this issue. How can Blob not be defined if the tests are running in the browser? And what can I do to fix this?

# jest.config.js
module.exports = {
    preset: 'jest-puppeteer',
    transform: {
        '^.+\\.ts$': 'ts-jest',
    },
};
# mylibrary.ts
function doSomething() {
  const blob = new Blob(...);
  return blob;
}
# mylibrary.spec.ts
it('should return a blob', function(){
    const b = doSomething();
    ...
});

Upvotes: 3

Views: 3416

Answers (3)

JStw
JStw

Reputation: 1205

Alternative I found is to use a "setup file" in the jest configuration file as below:

jest.config.js:

module.exports = {
    // ...
    preset: 'ts-jest',
    testEnvironment: 'node',
    // ...
    setupFiles: ['./src/setupTests.js']
};

setupTests.js:

global.Blob = () => {};

My test has compiled, this setup only bypass compilation error.

If you want to mock further you must adapt the setupTests.js global.Blob assignment by your mocked class.

Upvotes: 0

Colin D
Colin D

Reputation: 3111

I found that I needed to change testEnvironment from node to jsdom in my jest.config.json. My tests were I think default testEnvironment was jsdom but after using ts-jest it changed to node, so I changed it back to jsdom like this

Before

 module.exports = {
   preset: 'ts-jest',
   testEnvironment: 'node',
 };

after

 module.exports = {
   preset: 'ts-jest',
   testEnvironment: 'jsdom',
 }

Upvotes: 1

Thomas Dondorf
Thomas Dondorf

Reputation: 25240

jest-puppeteer allows you to use puppeteer. It will not automatically wrap your code (which should be running inside a browser) into a browser.

Code Sample

Here is an example how jest-puppeteer is supposed to be used:

it('...', async () => {
    await page.goto('...');
});

Problem Fix

If you want to test a whole website inside a browser, go with jest-puppeteer. Then you will need to launch a local server and use puppeteer to visit your website.

If you want to run a client-side library on the server, you might want to use polyfills. You can use blob-polyfill in your case.

Upvotes: 2

Related Questions