【问题标题】:Jest test creates empty blob objectJest 测试创建空的 blob 对象
【发布时间】:2021-11-07 02:46:59
【问题描述】:

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

有什么建议吗?

【问题讨论】:

  • _buildBlobForProperties() 没有从我看到的内容中返回承诺,所以为什么要等待?
  • 好点,很明显,一旦我为示例简化了它就不需要它了(我只是迁移我们的测试,大部分都没有写:P)

标签: javascript unit-testing jestjs blob


【解决方案1】:

Jest 测试环境不太支持Blob 对象,见issue#2555,建议你在测试环境中使用blob-polyfill 包对Blob 对象进行全局补丁。所以无论testEnvironmentjsdom还是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"

【讨论】:

    猜你喜欢
    • 2021-09-10
    • 1970-01-01
    • 2018-08-05
    • 2020-03-23
    • 2017-12-11
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    相关资源
    最近更新 更多