最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to mock a pdf Blob - Stack Overflow

programmeradmin0浏览0评论

Trying to create a valid pdf blob with no luck...

const blob = new Blob(["testing"], { type: "application/pdf" });
console.log(blob);

I did this because the typescript typing for new Blob() tells me the first argument is an array of BlobParts, which can be a string.

gives me this error:

Error {
      name: 'InvalidPDFException',
      message: 'Invalid PDF structure'
}

For reference, i'm trying to mock a valid pdf blob in a unit test

Trying to create a valid pdf blob with no luck...

const blob = new Blob(["testing"], { type: "application/pdf" });
console.log(blob);

I did this because the typescript typing for new Blob() tells me the first argument is an array of BlobParts, which can be a string.

gives me this error:

Error {
      name: 'InvalidPDFException',
      message: 'Invalid PDF structure'
}

For reference, i'm trying to mock a valid pdf blob in a unit test

Share Improve this question edited Nov 27, 2019 at 3:28 Lin Du 102k135 gold badges332 silver badges563 bronze badges asked Nov 27, 2019 at 2:08 NajiNaji 7322 gold badges18 silver badges36 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 16

Here is the solution:

index.ts:

export function main() {
  const blob = new Blob(["testing"], { type: "application/pdf" });
  console.log(blob);
}

index.spec.ts:

import { main } from "./";

describe("pdf blob", () => {
  it("should mock correctly", () => {
    const mBlob = { size: 1024, type: "application/pdf" };
    const blobSpy = jest
      // @ts-ignore
      .spyOn(global, "Blob")
      .mockImplementationOnce(() => mBlob);
    const logSpy = jest.spyOn(console, "log");
    main();
    expect(blobSpy).toBeCalledWith(["testing"], {
      type: "application/pdf"
    });
    expect(logSpy).toBeCalledWith(mBlob);
  });
});

Unit test result with 100% coverage:

 PASS  src/stackoverflow/59062023/index.spec.ts
  pdf blob
    ✓ should mock correctly (21ms)

  console.log node_modules/jest-mock/build/index.js:860
    { size: 1024, type: 'application/pdf' }

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 index.ts |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        4.736s, estimated 12s

Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59062023

发布评论

评论列表(0)

  1. 暂无评论