I have a working function that builds a new Blob() in my app
_buildBlobForProperties(app): Blob {
return new Blob(
[
JSON.stringify({
name: app.name,
description: app.description,
}),
],
{
type: 'application/json',
}
);
}
And I have the following test:
it('should return properties for update',() => {
const blob: Blob = appService._buildBlobForProperties(app);
expect(blob.text()).toBe(updateBlob.text());
});
This test works fine in Jasmin/Karma but when migrating the test to jest I get:
TypeError: blob.text is not a function
And when I print the content of the return Blob I get
console.log
---> Blob {}
Any suggestions?
Jest test environment doesn't support the Blob object very well, see issue#2555, I suggest you use blob-polyfill package to global patch Blob object in the test environment. So whether the testEnvironment is jsdom or node test environment, your test cases can pass.
service.ts:
export class AppService {
_buildBlobForProperties(app): Blob {
return new Blob([JSON.stringify({ name: app.name, description: app.description })], { type: 'application/json' });
}
}
service.test.ts:
import { Blob } from 'blob-polyfill';
import { AppService } from './service';
globalThis.Blob = Blob;
describe('69135061', () => {
test('should pass', async () => {
const appService = new AppService();
const app = { name: 'teresa teng', description: 'best singer' };
const blob: Blob = appService._buildBlobForProperties(app);
const text = await blob.text();
expect(text).toEqual(JSON.stringify(app));
});
});
jest.config.js:
module.exports = {
preset: 'ts-jest/presets/js-with-ts',
testEnvironment: 'jsdom',
// testEnvironment: 'node'
};
test result:
PASS examples/69135061/service.test.ts (8.044 s)
69135061
✓ should pass (3 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 8.092 s, estimated 9 s
Ran all test suites related to changed files.
package versions:
"ts-jest": "^26.4.4",
"jest": "^26.6.3",
"blob-polyfill": "^5.0.20210201"