Jest测试创建空Blob对象

k5ifujac  于 2022-12-08  发布在  Jest
关注(0)|答案(2)|浏览(206)

我有一个工作函数可以在我的应用中构建一个新的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 {}

有什么建议吗?

9o685dep

9o685dep1#

Jest测试环境对Blob对象的支持不是很好,参见issue#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"
uqjltbpv

uqjltbpv2#

您可以测试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' }
)

相关问题