如何模拟 pdf Blob

Naj*_*aji 2 javascript pdf unit-testing reactjs jestjs

试图创建一个有效的 pdf blob 没有运气...

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

我这样做是因为打字稿输入new Blob()告诉我第一个参数是一个数组BlobParts,它可以是一个字符串。

给我这个错误:

Error {
      name: 'InvalidPDFException',
      message: 'Invalid PDF structure'
}
Run Code Online (Sandbox Code Playgroud)

作为参考,我试图在单元测试中模拟一个有效的 pdf blob

sli*_*wp2 8

这是解决方案:

index.ts

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

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);
  });
});
Run Code Online (Sandbox Code Playgroud)

100% 覆盖率的单元测试结果:

 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
Run Code Online (Sandbox Code Playgroud)

源代码:https : //github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59062023