我有一个工作函数,在我的应用程序中构建一个新的Blob()
_buildBlobForProperties(app): Blob {
return new Blob(
[
JSON.stringify({
name: app.name,
description: app.description,
}),
],
{
type: 'application/json',
}
);
}
我有以下测试:
it('should return properties for update',() => {
const blob: Blob = appService._buildBlobForProperties(app);
expect(blob.text()).toBe(updateBlob.text());
});
这个测试在Jasmin/Karma中工作得很好,但是当将测试迁移到jest时,我得到:
TypeError: blob.text is not a function
当我打印返回Blob的内容时,我得到
console.log
---> Blob {}
有什么建议吗?
Jest测试环境不太支持Blob
对象,请参阅问题#2555,我建议您使用blob-polyfill包来全局修补测试环境中的Blob
对象。因此,无论testEnvironment是jsdom
还是node
测试环境,您的测试用例都可以通过。
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'
};
测试结果:
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.
包版本:
"ts-jest": "^26.4.4",
"jest": "^26.6.3",
"blob-polyfill": "^5.0.20210201"
您可以测试Blob是如何被调用的。
const TEST_BLOB_CONSTRUCTOR = jest.fn();
jest.spyOn(global, 'Blob').mockImplementationOnce((...args) => {
TEST_BLOB_CONSTRUCTOR(...args);
});
expect(TEST_BLOB_CONSTRUCTOR).toHaveBeenCalledWith(
[JSON.stringify({ name: EXPECTED_NAME, description: EXPECTED_APPLICATION })],
{ type: 'application/json' }
)